Recent projects often use HTML5 and Android and JS calls will often use, here record, test system more than 5.0.
Here first put the source code
Activity:
Package Jwzhangjie.com.webviewandjs;import Android.content.context;import Android.support.v7.app.appcompatactivity;import Android.os.bundle;import Android.view.view;import Android.webkit.javascriptinterface;import Android.webkit.webview;import Android.webkit.webviewclient;import Android.widget.toast;public class Mainactivity extends Appcompatactivity {private WebView WebView; @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (R.layout.activity_main); WebView = (WebView) Findviewbyid (R.id.webview); Initwebview (); } private void Initwebview () {//Set encoding Webview.getsettings (). Setdefaulttextencodingname ("Utf-8"); Support JS Webview.getsettings (). Setjavascriptenabled (True); Set the Listener event webview.setwebviewclient (new Jiewewviewclient ()); Sets the local calling object and its interface Webview.addjavascriptinterface (new Javascriptobject (Getapplicationcontext ()), "toandroid"); Load JS webview.loadurl ("file:///android_asset/index.html"); } public void Javacalljsnoparams (view view) {Webview.loadurl ("Javascript:javacalljsnoparamsmethod ()"); } public void Javacalljshasparams (view view) {Webview.loadurl ("Javascript:javacalljshasparamsmethod ('" + 123 + ") ‘)"); } public class Javascriptobject {Context mcontxt; Public Javascriptobject (Context mcontxt) {this.mcontxt = Mcontxt; } @JavascriptInterface//sdk17 version number above plus annotated public void Jscalljavanoparams () {Toast.maketext (mcontxt , "JS calls Java Method (no participation)", Toast.length_long). Show (); } @JavascriptInterface//sdk17 version number plus annotated public void Jscalljavahasparams (String params) {toast.ma Ketext (Mcontxt, "JS calls the Java method (with references):" + params, toast.length_short). Show (); }} class Jiewewviewclient extends webviewclient{/** * assumed to be followed by * Webview.loadurl ("File:///an Droid_asset/index.html "); * The method of invoking JS is not working, must be loaded on the page is sufficient */@Override public void onpagefinished (WebView view, String URL) {super.onpagefinished (view, URL); Webview.loadurl ("Javascript:javacalljshasparamsmethod ('" + 123 + "')"); } }}
Html:
<! DOCTYPE html>Interface:
Note the point:
1, Android system 17 and above, JS call Java need to add @javascriptinterface on the method
2, can not be loaded into the HTML page of the following direct invocation of the JS method, should be loaded in the Webviewclient onpagefinished, the principle is that the HTML must be loaded after completion. Ability to invoke the method in JS.
Source code: http://download.csdn.net/download/jwzhangjie/9020941
Android and JS call each other and note