Simple Android Java & JavaScript Bridge

来源:互联网 发布:迅雷5.8绿色优化版 编辑:程序博客网 时间:2024/06/17 13:54

Simple Android Java & JavaScript Bridge

by sachin lende March 29, 2013

 Communicate between Android-Java & JavaScript 

While developing mobile app sometimes we need to use webview & HTML page & we want to communicate between JS & Java. Below is example demonstrates how to call JS function when button from android is clicked and also how to call android native method by click event on button from HTML page.

Above is main screen with android native button “Call JS Fn”, when we select this button it will call method with name “javaFnCall” from JavaScript interface “JsHandler.java”. Below is code for “MainActivity.java” & layout “activity_main”.

/**A screen that holds webview, android-native button to call JS function.MainActivity.java*/public class MainActivity extends Activity implements OnClickListener{private WebView webView;private Button btn;private JsHandler _jsHandler;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);btn = (Button)findViewById(R.id.button1);btn.setOnClickListener(this);initWebView();}/** * Function initializes  webview & does the necessary settings for webview */private void initWebView(){webView = (WebView)findViewById(R.id.webviewId);//Tell the WebView to enable javascript execution.webView.getSettings().setJavaScriptEnabled(true);webView.setBackgroundColor(Color.parseColor("#808080"));//Set whether the DOM storage API is enabled.webView.getSettings().setDomStorageEnabled(true);//setBuiltInZoomControls = false, removes +/- controls on screenwebView.getSettings().setBuiltInZoomControls(false);webView.getSettings().setPluginState(PluginState.ON);webView.getSettings().setAllowFileAccess(true);webView.getSettings().setAppCacheMaxSize(1024 * 8);webView.getSettings().setAppCacheEnabled(true);_jsHandler = new JsHandler(this, webView);webView.addJavascriptInterface(_jsHandler, "JsHandler");webView.getSettings().setUseWideViewPort(false);webView.setWebChromeClient(new WebChromeClient());webView.setWebViewClient(new WebViewClient() {@Overridepublic void onPageStarted(WebView view, String url, Bitmap favicon) {// TODO Auto-generated method stubsuper.onPageStarted(view, url, favicon);//Toast.makeText(TableContentsWithDisplay.this, "url "+url, Toast.LENGTH_SHORT).show();}@Overridepublic void onPageFinished(WebView view, String url) {super.onPageFinished(view, url);//Toast.makeText(TableContentsWithDisplay.this, "Width " + view.getWidth() +" *** " + "Height " + view.getHeight(), Toast.LENGTH_SHORT).show();}@Overridepublic void onReceivedSslError(WebView view,SslErrorHandler handler, SslError error) {// TODO Auto-generated method stubsuper.onReceivedSslError(view, handler, error);//Toast.makeText(TableContentsWithDisplay.this, "error "+error, Toast.LENGTH_SHORT).show();}});// these settings speed up page load into the webviewwebView.getSettings().setRenderPriority(RenderPriority.HIGH);webView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);webView.requestFocus(View.FOCUS_DOWN);                       // load the main.html file that kept in assets folderwebView.loadUrl("file:///android_asset/main.html");}@Overridepublic void onClick(View v) {switch (v.getId()) {case R.id.button1:_jsHandler.javaFnCall("Hey, Im calling from Android-Java");break;default:break;}}}

Below is the JavaScript Interface that will actually handles the communication between Java & JavaScript.

/** * Class to handle all calls from JS & from Java too **/public class JsHandler {Activity activity;String TAG = "JsHandler";WebView webView;public JsHandler(Activity _contxt,WebView _webView) {activity = _contxt;webView = _webView;}/** * This function handles call from JS */public void jsFnCall(String jsString) {showDialog(jsString);}/** * This function handles call from Android-Java */public void javaFnCall(String jsString) {final String webUrl = "javascript:diplayJavaMsg('"+jsString+"')";// Add this to avoid android.view.windowmanager$badtokenexception unable to add windowif(!activity.isFinishing()) // loadurl on UI main threadactivity.runOnUiThread(new Runnable() {@Overridepublic void run() {webView.loadUrl(webUrl); }});}/** * function shows Android-Native Alert Dialog */public void showDialog(String msg){AlertDialog alertDialog = new AlertDialog.Builder(activity).create();  alertDialog.setTitle(activity.getString(R.string.app_dialog_title));alertDialog.setMessage(msg);  alertDialog.setButton(DialogInterface.BUTTON_POSITIVE,activity.getString(R.string.ok_text), new DialogInterface.OnClickListener() {  public void onClick(DialogInterface dialog, int which) {  dialog.dismiss();}}); alertDialog.setButton(DialogInterface.BUTTON_NEGATIVE,activity.getString(R.string.cancel_text), new DialogInterface.OnClickListener() {@Overridepublic void onClick(DialogInterface dialog, int which){dialog.dismiss();}}); alertDialog.show();}}

When we click on button from HTML page “Call Java Fn” which is loaded into webview, it will call android’s native function jsFnCall(String jsString) using JavaScript handler “JsHandler” passed to webivew. Result of this display android’s native alert dialog with message “Calling from Java Script”.

Below is the main.html file kept in “assets” folder. Load this file to webview using webView.loadUrl(“file:///android_asset/main.html”);

<!DOCTYPE html><html> <head>  <script language="javascript">>  function diplayJavaMsg(msg){  alert(msg);  }  function callTojavaFn(){  var msg = "Calling from Java Script";  JsHandler.jsFnCall(msg);  }  </script> </head> <body><input type="button" onClick="callTojavaFn()" value="Call Java Fn"> </body></html>

0
Share
<iframe frameborder="0" hspace="0" marginheight="0" marginwidth="0" scrolling="no" tabindex="0" vspace="0" width="100%" id="I0_1430386204468" name="I0_1430386204468" src="https://apis.google.com/u/0/se/0/_/+1/sharebutton?plusShare=true&amp;usegapi=1&amp;action=share&amp;annotation=vertical-bubble&amp;hl=en-US&amp;origin=http%3A%2F%2Fwww.cuelogic.com&amp;url=http%3A%2F%2Fwww.cuelogic.com%2Fblog%2Fsimple-android-java-javascript-bridge%2F&amp;gsrc=3p&amp;jsh=m%3B%2F_%2Fscs%2Fapps-static%2F_%2Fjs%2Fk%3Doz.gapi.zh_CN.Ou9Xe2sOOCw.O%2Fm%3D__features__%2Fam%3DIQ%2Frt%3Dj%2Fd%3D1%2Ft%3Dzcms%2Frs%3DAGLTcCPXuIFLAOQGifuHvi6gmzcNfIaNkA#_methods=onPlusOne%2C_ready%2C_close%2C_open%2C_resizeMe%2C_renderstart%2Concircled%2Cdrefresh%2Cerefresh%2Conload&amp;id=I0_1430386204468&amp;parent=http%3A%2F%2Fwww.cuelogic.com&amp;pfname=&amp;rpctoken=54453298" data-gapiattached="true" title="+Share" style="box-sizing: border-box; display: block !important; margin: 0px; position: static; top: 0px; width: 63px; border-style: none; left: 0px; visibility: visible; height: 60px;"></iframe>
This entry was posted in Mobile and tagged androidjava js bridgejavascriptwebview on March 29, 2013 by sachin lende.

0 0