Jsbridge implements the mutual invocation of JavaScript and Android __java

Source: Internet
Author: User
Tags stub

Android's WebView is based on the WebKit kernel, WebView integrates JS and Java interface functions, through addjavascriptinterface (Object obj, String InterfaceName) method, Java classes can be registered into the WebKit, to the Web page JS on the call, but also through the loadurl (String URL) method is to WebKit pass a URI, For the browser to parse, implementation of Java and JS methods of interaction.

For more detailed documentation, refer to the Android developers for more information on WebView, which is linked as follows: http://developer.android.com/guide/webapps/webview.html

Here is a simple example to illustrate the interaction between WebView and JS process, such as the lack of written areas, welcome everyone to Pat Bricks.

Webviewdemo source code is as follows:

Import Android.annotation.SuppressLint;
Import android.app.Activity;
Import Android.app.AlertDialog;
Import Android.content.DialogInterface;
Import Android.graphics.Bitmap;
Import Android.os.Bundle;
Import Android.os.Handler;
Import Android.util.Log;
Import Android.webkit.JavascriptInterface;
Import Android.webkit.JsPromptResult;
Import Android.webkit.JsResult;
Import android.webkit.WebChromeClient;
Import android.webkit.WebSettings;
Import Android.webkit.WebView;
Import android.webkit.WebViewClient;

Import Android.widget.Toast;
	
	public class Webviewdemo extends activity {public static final String TAG = WebViewDemo.class.getSimpleName ();
	Private Handler Mhandler = new Handler ();  
	
	Private WebView Mwebview;
		@Override protected void OnCreate (Bundle savedinstancestate) {Setcontentview (r.layout.activity_main);
		
		Super.oncreate (savedinstancestate);  
	Initview (); @SuppressLint ("setjavascriptenabled") private void Initview () {Mwebview = (WebView) Findviewbyid (R).Id.mwebview);  
        WebSettings almost all settings in the browser are websettings in this class websettings = Mwebview.getsettings ();  
        Websettings.setsavepassword (FALSE);  
        Websettings.setsaveformdata (FALSE);  
        Websettings.setjavascriptenabled (TRUE);  
        
        Websettings.setsupportzoom (FALSE);
        Mwebview.setwebviewclient (New Mywebviewclient ());  
        Mwebview.setwebchromeclient (New Mywebchromeclient ()); 
         * * Demojavascriptinterface class for JS call to the Android server to provide interface * Android as the Demojavascriptinterface class client interface is called JS * The specific method of the invocation is defined in Demojavascriptinterface: * For example, clickonandroid/Mwebview.addjavascrip in this instance  
        Tinterface (New Demojavascriptinterface (), "Android");
	Mwebview.loadurl ("file:///android_asset/page.html"); /** * Inherits the Webviewclient class, handles the WebView page loading, the page loading, the page loading error, URL interception and other events processing * @author bingbing Feng */FINAL class my Webviewclient extends webviewclient{@Override public boolean shouldoverrideUrlloading (webview view, String URL) {log.i (TAG, "shouldoverrideurlloading url=" +url);
		Return super.shouldoverrideurlloading (view, URL); @Override public void onpagestarted (webview view, String URL, Bitmap favicon) {log.i (TAG, onpagestarted url=) +
			URL);
		super.onpagestarted (view, URL, favicon);
			@Override public void onpagefinished (webview view, String URL) {log.i (TAG, "onpagefinished url=" +url);
		super.onpagefinished (view, URL);
			@Override public void Onreceivederror (webview view, int errorcode, string description, String failingurl) {
			LOG.E (TAG, "Onreceivederror errorcode=" +errorcode);
		Super.onreceivederror (view, errorcode, description, Failingurl); }/** * Inherits Webchromeclient class, handles JS popup event * @author bingbing Feng * * * */FINAL class Mywebchromeclient ex Tends webchromeclient {@Override public void onprogresschanged (webview view, int newprogress) {log.i (TAG, "Onpro Gresschanged newprogress= "+newprogress);
			Super.onprogresschanged (view, newprogress); @Override public boolean Onjsalert (WebView view, string URL, string message, jsresult result) {log.i (TAG, "
            Onjsalert message= "+message);  
                The simple encapsulation of alert is new Alertdialog.builder (Webviewdemo.this). Settitle ("Alert"). Setmessage (Message). Setpositivebutton ("OK", new Dialoginterface.onclickli  
                    	Stener () {@Override public void OnClick (dialoginterface arg0, int arg1) {
            TODO auto-generated Method stub}}) . Setnegativebutton ("Cancel", new Dialoginterface.onclicklistener () {@Override public void OnClick (Dialo  
            Ginterface dialog, int which) {//TODO auto-generated method stub}}. Create (). Show ();  Result.confirm ();  
		Must not less return true; } @Override PUBlic Boolean onjsconfirm (webview view, string URL, string message, jsresult result) {log.i (tagged, "onjsalert message
			= "+message");
		Return super.onjsconfirm (view, URL, message, result); @Override public boolean onjsprompt (WebView view, string URL, String message, string defaultvalue, Jspromptresu
			Lt result) {log.i (TAG, "Onjsalert message=" +message);
		Return super.onjsprompt (view, URL, message, defaultvalue, result); } Final class Demojavascriptinterface {Demojavascriptinterface () {}/** * 
         This method is invoked by the browser side * caution:if You ' ve set your targetsdkversion to or higher, and you must add the @JavascriptInterface */@JavascriptInterface public void Clickonandroid () {mhandler.post () (New runnabl E () {public void run () {//native calls the Onjsandroid method in JS Mwebvi  
                Ew.loadurl ("javascript:onjsandroid ()");  
    }        });  /** JS calls the native method to display a toast/@JavascriptInterface public void Showtoast (String toast)
        {Toast.maketext (Getapplicationcontext (), Toast, Toast.length_short). Show ();
 }
    }  
}


Bind a callback to the proxy class javascriptinterface, and give it a call to the name of Android

Mwebview.addjavascriptinterface (New Demojavascriptinterface (), "Android");  

WebView addjavascriptinterface (Object obj, String InterfaceName) provides a callback interface for JavaScript, which should be noted that it must be implemented in a separate thread without blocking the thread.
Addjavascriptinterface (Object obj, String InterfaceName) obj represents a Java object, where we typically implement a class of our own that provides the method we want to provide to JavaScript access , InterfaceName is the JS object used to access the method we declared in obj, and the invocation pattern is window.interfacename. Method Name ().

With log information, we find that the method in the callback interface (the method provided to JavaScript access in the OBJ object) runs in a thread named Webviewcorethread, rather than the main thread (UI thread), if some time-consuming operation is required in the callback method, It is recommended that you perform these time-consuming operations in a new thread.

Java Call HTLM page in the JS method, just know the JS method name can:

Mwebview.loadurl ("javascript:onjsandroid ()");  

Next, let's look at how to tune the native method in an HTML page, with the sample code as follows:

<! DOCTYPE html>


Here WebView and JS Interaction has been completed, we can experiment.





Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.