1.html Code
<Scripttype= "Text/javascript"> function Javacalljs() {document.getElementById ("content"). InnerHTML= "Java calls the parameterless function of JS"; } functionJavacalljswith (Arg) {document.getElementById ("content"). InnerHTML=(ARG); }</Script> <inputtype= "button"value= "Click Invoke Java Code"onclick= "Window.android1.jsCall ()" /> <inputtype= "button"value= "Click Invoke Java code and pass parameters"onclick= "window. android1. Jscall (' Paramsvalue ') " />
2.java Code
Importandroid.app.Activity;ImportAndroid.app.AlertDialog;ImportAndroid.os.Bundle;ImportAndroid.webkit.JavascriptInterface;ImportAndroid.webkit.WebView;ImportAndroid.widget.Toast;ImportButterknife. BindView;ImportButterknife. Butterknife;ImportButterknife. OnClick;/*** Android and JS call each other * layout file for 2 button, one webview*/ Public classActivitywebviewextendsActivity {@BindView (r.id.webview) WebView WebView; @Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate); Setcontentview (r.layout.activity_ble); Butterknife.bind ( This); Webview.loadurl ("Http://192.168.61.104:8080/update/android_js.html"); webview.getsettings (). setjavascriptenabled ( true);//enable JavaScript webview.addjavascriptinterface (this, "android1"); Android1 is an alias in HTML } /*** Functions that are called by JS*/@JavascriptInterface Public voidJscall () {Runonuithread (NewRunnable () {@Override Public voidrun () {Toast.maketext (Activitywebview. This, "parameter-free method is called by JS", Toast.length_short). Show (); } }); } /*** The function called by JS Jscall * Jscall This is the function name in the HTML * must be added @JavascriptInterface this annotation*/@JavascriptInterface Public voidJscall (FinalString params) {Runonuithread (NewRunnable () {@Override Public voidrun () {NewAlertdialog.builder (Activitywebview. This). Setmessage (params). Show (); } }); } @OnClick (R.id.btn0) Public voidbtn0 () {Webview.loadurl ("Javascript:javacalljs ()");//Call the function name of Js:javacalljs with no argument} @OnClick (R.ID.BTN1) Public voidbtn1 () {String params= "params";//call the function name with the parameter Js:javacalljswith as JS, the params is the argument valueWebview.loadurl ("Javascript:javacalljswith ('" + params + ")"); }}
Reference: http://blog.csdn.net/leejizhou/article/details/50894531/
Android and JS Interaction