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; @Override protected 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 screen webView.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() { @Override public void onPageStarted(WebView view, String url, Bitmap favicon) { // TODO Auto-generated method stub super.onPageStarted(view, url, favicon); //Toast.makeText(TableContentsWithDisplay.this, "url "+url, Toast.LENGTH_SHORT).show(); } @Override public void onPageFinished(WebView view, String url) { super.onPageFinished(view, url); //Toast.makeText(TableContentsWithDisplay.this, "Width " + view.getWidth() +" *** " + "Height " + view.getHeight(), Toast.LENGTH_SHORT).show(); } @Override public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) { // TODO Auto-generated method stub super.onReceivedSslError(view, handler, error); //Toast.makeText(TableContentsWithDisplay.this, "error "+error, Toast.LENGTH_SHORT).show(); } }); // these settings speed up page load into the webview webView.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 folder webView.loadUrl("file:///android_asset/main.html"); } @Override public 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 window if(!activity.isFinishing()) // loadurl on UI main thread activity.runOnUiThread(new Runnable() { @Override public 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() { @Override public 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>