Before the project did some of the JS interaction between Android and HTML5 things, today there is time to summarize:
First, why to do JS interaction:
In order to facilitate native development and data transfer between HTML, in the case of static pages can change the original development of the page;
Second, how to do JS interaction:
(i) The Android side calls the H5 page
The main use of WebView on the Android side for Web page loading, setting properties
// Get Websetting Object WebSettings websettings = webview.getsettings (); // set support JavaScriptwebsettings.setjavascriptenabled (true); // The class object defined in Android Androidjs exposed to JavaScript
Webview.addjavascriptinterface (new Androidjs (mainactivity. this"androidjs");
How to call: where DoAlert is the H5 page method
Webview.loadurl ("javascript:doalert ()");
(ii) H5 end call Android page
H5-Side code:
<input type="button" value=" greeting " onclick=" Androidjs.showtoast ()"/><input type="button" value=" Book list " onclick="androidjs.showlist ()"/>
Android Side code:
Public classAndroidjs {PrivateContext Mcontext; PublicAndroidjs (Context context) { This. Mcontext =context; } @JavascriptInterface Public voidshowlist () {NewAlertdialog.builder (Mcontext). Settitle ("List of Books"). SetIcon (R.mipmap.ic_launcher). Setitems (Newstring[]{"Crazy Java Handouts","Crazy Android Handout", "lightweight Java EE Development"},NULL). Setpositivebutton ("Determine",NULL). Create (). Show (); } @JavascriptInterface Public voidShowtoast () {Toast.maketext (Mcontext,"Hello", Toast.length_long). Show (); }}
Note: Androidjs is a bridge identifier that connects Android with HTML, and is also a class for interacting with the data;
Note: The method in this must be common, and the class name is consistent with the identity;
The above is a simple JS interactive process, note the place to pay special attention, please advise
JS interaction between Android and H5