Sometimes we have a need to listen to some of the events of the controls in the HTML. For example, click a button in the HTML to jump to another activity and copy a paragraph of text.
The first is the setting for WebView:
Mywebview = (WebView) Findviewbyid (R.id.mywebview); Mywebview.getsettings (). setjavascriptenabled (true); Mywebview.addjavascriptinterface (new javascriptinterface (this), "Android" ); Mywebview.setwebviewclient (new mywebviewclient ());
To create the Javascriptinterface class:
Public class Javascriptinterface { context context; Public javascriptinterface (context c) { context= c; } /** * The method used to interact with JS, in JS directly call the */ @JavascriptInterface publicvoid showtoast (String ssss) { toast.maketext (Mcontext, SSSs, Toast.length_long). Show (); }}
Add @javascriptinterface annotations to a method that allows JS to be called in a higher version
Then use WebView's addjavascriptinterface to add the object of this class and take a name.
<script type= "Text/javascript" > function showtoast () { android.showtoast ("haha aha" ); } </script> onClick= "showtoast ()"/ ></body>
The HTML code is simple, and the native method can be successfully invoked using Android.shwotoast ("") in the JS method that wants to invoke the native method. We can use it to copy information, get click events, and so on. (Shwotoast is the native method name, and Android is the name we define in the Addjavascriptinterface method).
From:im mi
Calling Android native method via JS