Simple Android Java & JavaScript Bridge

bysachin 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
This entry was posted in Mobile and tagged android , java js bridge , javascript , webview on March 29, 2013 bysachin lende .

更多相关文章

  1. 代码中设置drawableleft
  2. android 3.0 隐藏 系统标题栏
  3. Android开发中activity切换动画的实现
  4. Android(安卓)学习 笔记_05. 文件下载
  5. Android中直播视频技术探究之—摄像头Camera视频源数据采集解析
  6. 技术博客汇总
  7. android 2.3 wifi (一)
  8. AndRoid Notification的清空和修改
  9. Android中的Chronometer

随机推荐

  1. android studio 查看sha1(Mac windows下的
  2. Android(安卓)layer-list的属性和使用详
  3. 虹软免费人脸识别 Demo [Android]
  4. Android引导页播放视频——使用VideoView
  5. android实现Uri获取真实路径转换成File的
  6. Android(安卓)adb down
  7. 整理:控件之间的冲突
  8. Android——requestWindowFeature
  9. Android(安卓)ListView分页显示
  10. Android(安卓)Kotlin intent.getStringEx