In android WebView and javascript implement data interaction instances

  • 2020-06-01 10:59:08
  • OfStack

You must have an javascript foundation before you can understand this article.

(1) js calls android's method:

WebView wView ; 
wView. addJavascriptInterface (Object obj, String interfaceName);

Is to instantiate an object, called in html's js, and the second parameter is the alias of the instantiated object, the name used in js if this obj is to be used
Is interfaceName.
public class jsWebDemo extends Activity {   
    WebView wView ;     /** Called when the activity is first created. */ 
    public void onCreate(Bundle savedInstanceState) {  
        wView = (WebView)findViewById(;  
       WebSettings wSet = wView.getSettings();  
        wSet.setJavaScriptEnabled(true);          ProxyBridge pBridge = new ProxyBridge();  
        wView.addJavascriptInterface(pBridge, "AliansBridge");  
 private class ProxyBridge {  
  public int one () {  
   return 1;  

Let's take a look at 1. index.html:

  <mce:script language="javascript"><!--
        /* This function is invoked by the activity */  
        function wave() {  
// --></mce:script>
<div id="output">Test page.</div>      <a onClick="window.demo.clickOnAndroid()">
 <div style="width:100px;  
            margin:0px auto;  
            border:2px solid #202020;" > 
                <img id="droid" src="android_normal.png" mce_src="android_normal.png"/><br> 
                Click me!  
<input type="submit" value="change to 1" onclick="document.getElementById('output').innerHTML" />     

Here, AliansBridge is the JAVA object being invoked.
Note that if you only have 1 method that needs to be called by js and only new1 object:
ProxyBridge pBridge = new ProxyBridge();
wView.addJavascriptInterface(pBridge, "AliansBridge");
If you need to call multiple methods, you need to instantiate the entire android class itself:
wView.addJavascriptInterface(this, "AliansBridge");
(2) android calls js method: wView.setWebChromeClient (WebChromeClient client)
To update UI, Handler mHandler = new Handler();
mWebView.setWebChromeClient(new MyWebChromeClient());                
    mWebView.addJavascriptInterface(new Object(){
     * This is not called on the UI thread. Post a runnable to invoke     
     * loadUrl on the UI thread.     
    public void clickOnAndroid() {       Runnable() {        
            public void run() {        
 }, "demo");

Similarly, in html there must be an object called demo that calls the clickOnAndroid() method.
 * Provides a hook for calling "alert" from javascript. Useful for     
 * debugging your javascript.     
final class MyWebChromeClient extends WebChromeClient {        
    public boolean onJsAlert(WebView view, String url, String message,     
            JsResult result) {                     
    return super.onJsAlert(view, url, message, result);                       

Related articles: