JavaScript calls Java and javascriptjava
1. Map a Java object to a JavaScript Object
MainActivity. java
Package com. example. jsdemo; import android. OS. bundle; import android. support. v7.app. appCompatActivity; import android. webkit. webSettings; import android. webkit. webView; public class MainActivity extends AppCompatActivity {private WebView wView; @ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); wView = (WebView) findViewById (R. id. wView); wView. loadUrl ("file: // android_asset/demo1.html"); WebSettings webSettings = wView. getSettings (); // ① set WebView to allow the call of js webSettings. setJavaScriptEnabled (true); webSettings. setDefaultTextEncodingName ("UTF-8"); // sets support for js calls java wView. addJavascriptInterface (new AndroidAndJSInterface (), "Android" ");} class AndroidAndJSInterface {@ JavascriptInterface public void showToast () {Toast. makeText (MainActivity. this, "I have been called by js", Toast. LENGTH_SHORT ). show ();}}}
Note: The WebView. addJavascriptInterface interface does not work in two ways.
① Change the version to 16
(2) Add the @ JavascriptInterface annotation to the method of the JavaScript interface class.
2. Example of JavaScript calling a Java object
Demo1.html
<Input type = "button" value = "Click Android to be called" onclick = "window. Android. showToast ()"/>