How does JavaScript interact with Android programs? I encountered this problem in the project a few days ago. In fact, it is much simpler. There is only one thing to note, that is, the compatibility between JavaScript and Android. Here we will summarize how JavaScript calls Android and Android to JavaScript.
First, set the attributes of WebView. If you want this Webview to interact directly with JavaScript, you must set its setJavaScriptEnabled to true. The following code is as follows:
Webview = (WebView) this. findViewById (R. id. webView1); WebSettings webSetting = webview. getSettings (); webSetting. setJavaScriptEnabled (true); // whether javaScript is supported
1. JavaScript calls the Android Program
JavaScript calls the Androd program requires an interface provided by the Android program. In my opinion, the Android interface called by JavaScript is a bit similar to callback. The details are as follows:
Let the webviewdomaindemo.html webpage set a button in the webpage. When a click button is clicked, The androidinterface is used. demo.html is as follows:
<Script type = "text/javascript"> function jsToAndriod () {var msg = 'jstoandriod '; javascript: android. getResult (msg);} function androidToJs () {var msg = 'androidtojs'; alert (msg) ;}</script> In Android, the following code is required to define the interface called by JavaScript:
Step 1: first register the interface provided for JavaScript call
webview.addJavascriptInterface(new JavaScriptinterface(), "android");
Step 2: Define the interface
class JavaScriptinterface{@JavascriptInterfacepublic void getResult(String str){Log.e("","result = " + str);}}
2. Android calls the JavaScript Interface
As you can see, demodemo.html has an interface called androidToJs. Yes, in JavaScript, this interface is declared and defined. In android, you only need to call it like this:
Webview. loadUrl ("javascript: androidToJs ()"); // call in UI Thread in js!Note that it is called in the main thread. Otherwise, an exception occurs.
3. compatibility issues with JavaScript and Android versions
If you are careful enough, you can see that there is a comment @ JavascriptInterface on the Android interface jsToAndroid () when defining JavaScript to call the Android interface, otherwise, JavaScript may not be able to call the Android interface. An error is reported indicating that this interface is not defined.