First, JS and Android
Placed under the Assets folder (note that if you are using as the Ide,assets folder should be placed in the Src/main directory)
<!DOCTYPE HTML><HTML> <Head> <MetaCharSet= "Utf-8"> <title>Geff</title> <Script> functioncallandroid () {Test.hello ("JS calls the Hello method in Android"); } </Script> </Head> <Body> <Buttontype= "button"ID= "Button1"onclick= "callandroid ()">JS calls the code in Android</Button> </Body></HTML>
The code is very simple, the page is a button, click on this button to call the Callandroid function, it is important to note that the statement in the Callandroid function is an external function of Android, the code in Android:
{ ... Websettings.setjavascriptenabled (true); Webview.addjavascriptinterface (This, "test"); // corresponding to the test.xxx in JS Webview.loadurl ("file:///android_asset/js_web.html");} @JavascriptInterfacepublicvoid Hello (String msg) {// corresponds to JS in Xxx.hello ("" ) log.e ("WebView", "Hello"); Toast.maketext (this, Msg,toast.length_long). Show ();}
It is important to note that the Hello function plus the annotation @javascriptinterface, so clicking on the button in the HTML will invoke the Hello method in Android.
Second, the Android call JS code
The JS code is as follows:
<script> function calljs () { alert ("Android calls the Calljs method in JS"); } </script>
The Android code is as follows:
void Click (View view) { webview.post (new Runnable () { @Override void Run () { Webview.loadurl ("Javascript:calljs ()"); } });
When the button in Android is clicked, the click Method is triggered, then the Webview.loadurl ("Javascript:calljs ()") is executed, then the Calljs method is exactly the same in JS, then the alert () is executed.
This concludes very well:
Https://github.com/shaojiankui/iOS-WebView-JavaScript
JS and iOS, Android interaction