- Search a simple example, found a lot of code snippets, but not without a complete project, a little tidying up for those who first contact JS and Java call each other classmate. The article finally has the project source address.
- JS Call Java Method Example
<html><body> <script language="javascript"> function javacalljsfunction(ishide) {var x = document.getElementById (' div '); X.classname = ""; } function js2java() { jsinterface.javafunction (); } </script> <style type="Text/css"> . Hide { display: none;} </style> <input type="button" onClick="Js2java ()"style ="height:200px; width:200px " value=" Call Java Fn "> <div class="Hide" id="div"> <font color="#FF0000">This is a hide div~~~~</font> </div></body>
- JS Call Java Method parsing
function js2java() { JSInterface.javaFunction();}
Where Jsinterface is the alias of the native class, equivalent to the instance in Java, Javafunction is the method that is declared inside the native class; note that the Android API Versions 17 and later need to be annotated @javascriptinterface in the method needs declaration.
-java receiving JS calls and invoking sample code
Public class jsinterface { PrivateWebView Mwebview; Public Jsinterface(WebView WebView) { This. Mwebview = WebView; }@JavascriptInterface Public void javafunction() {NewHandler (Looper.getmainlooper ()). Post (NewRunnable () {@Override Public void Run() {//update UI in main looper, or it'll crashToast.maketext (Mwebview.getcontext (),"Javafunction had been called", Toast.length_short). Show (); } }); } Public void javacalljsfunction(intCode) {Mwebview.loadurl (String.Format ("Javascript:payerror ("+code+")")); }}
- function Javacalljsfunction calling JS code for Java
Finally, the source code for the example project: Android-js-call
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
A simple demo teaches you: Android and JS call each other