Html5,js and Android native communication

Source: Internet
Author: User

Overview

What is H5,js and Android communication? In fact, that is, JS calls the Android local method and the Android local call JS method between a process. This article is mainly about a simple way of communication, as for the communication between the data Protocol I use JSONRPC, here do not do too much description, do not understand the self-access, because most people do not use this when communicating.

WebView settings

This should not be a problem, the approximate setting is a few basic items, where the code is posted, there is nothing special.

Private void Initwebview() {WebSettings websettings = webview.getsettings (); Websettings.setjavascriptenabled (true); Websettings.setdatabaseenabled (true);//Websettings.setdatabasepath ("/data/data/" + Envi.appContext.getPackageName () + "/localstorage/");Websettings.setdomstorageenabled (true); Websettings.setsavepassword (false); Websettings.setsaveformdata (true); Websettings.setsupportzoom (false); Websettings.setgeolocationenabled (true); Websettings.setdomstorageenabled (true); Websettings.setappcacheenabled (true); Websettings.setallowfileaccess (true);//websettings.setappcachemaxsize (* * 1024x768);//Websettings.setappcachepath ("/data/data/" + Envi.appContext.getPackageName () + "/cache/");//Websettings.setcachemode (Websettings.load_default);//String useragent = websettings.getuseragentstring ();//useragent = useragent + "Ganji_" + Envi.customerid + "_" + envi.versionname;//Websettings.setuseragentstring (useragent);}

Here you can annotate/open some settings as required.

Webview.setwebviewclient (NewWebviewclient () {@Override             Public void Onloadresource(WebView view, String URL) {Super. Onloadresource (view, URL); }@Override             Public Boolean shouldoverrideurlloading(WebView view, String URL) {return Super. shouldoverrideurlloading (view, URL); }@Override             Public void Onreceivederror(WebView view,intErrorCode, string description, String failingurl) {LOG.E ("HTML5","WebView receive error:"+ description);Super. Onreceivederror (view, ErrorCode, description, Failingurl); Mwebviewreceivederror =true; }@Override             Public void onpagefinished(WebView view, String URL) {mpageloadfinished =true;if(Mwebviewreceivederror) {//todo network is OK?Webview.post (NewRunnable () {@Override                         Public void Run() {webview.setvisibility (view.gone);//Mloadfailcontainer.setvisibility (view.visible);}                    }); }            }@Override             Public void onpagestarted(WebView view, String URL, Bitmap favicon) {Super. onpagestarted (view, URL, favicon);        }        }); Webview.setwebchromeclient (NewWebchromeclient () {@Override             Public void ongeolocationpermissionsshowprompt(String origin, Geolocationpermissions.callback Callback) {Callback.invoke (Origin,true,false);Super. Ongeolocationpermissionsshowprompt (Origin, callback); }@Override             Public Boolean Onjsalert(WebView view, string URL, string message, jsresult result) {return true; }@Override             Public Boolean onjsconfirm(WebView view, string URL, string message, jsresult result) {return true; }@Override             Public Boolean onjsprompt(WebView view, string URL, String message, string defaultvalue, jspromptresult result) {return true; }@Override             Public void Onexceededdatabasequota(string URL, String databaseidentifier,LongQuotaLongEstimateddatabasesize,LongTotalquota, Webstorage.quotaupdater quotaupdater) {QUOTAUPD Ater.updatequota (Estimateddatabasesize *2); }@Override             Public void onreachedmaxappcachesize(LongRequiredstorage,LongQuota, Webstorage.quotaupdater quotaupdater) {Quotaupdater.updatequota (Requiredstorage *2); }        });

There is no need for reference, mainly to two client settings, according to your needs.

Native Call JS method

The following point, JS call native method, first, I put down my JS code:

<! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd "><html xmlns="http://www.w3.org/1999/xhtml"> <head>  <meta http-equiv="Content-type" Content="text/html; Charset=utf-8 " />    <script>  function showinfo(str) { document.getElementById ("info")          /c5>). Innerhtml=str; }                </script>  </head>      <body>The values coming from Android are:<span id="Info"> </span>        <br>          <a href="#" onclick="window. Gjnativeapi.callandroid (' I am come from Android. ') ' >Call Android from JavaScript</a>      </body>  </html>

The important thing here is that to define the name of the function method, the native call is based on that call. I call it in a button click event:

btn.setOnClickListener(new View.OnClickListener() {            @Override            publicvoidonClick(View v) {                //调用此语句,调用js里的方法                webView.loadUrl("javascript:showInfo(‘hello js‘)");            }        });

This will dig into a native call JS method. The focus is on the JS method name, and the Android JavaScript: After the method name is the same.

JS Call native method

This also makes an additional setting for the WebView:

mWebView.addJavascriptInterface(new"GJNativeAPI");

Then let's see what this gjnativeapi is:

/**     * 供 js 调用的本地对象     */    publicclass GJNativeAPI {        /**         * js 调用该方法发起 rpc 调用,或者返回 rpc 响应         */        @JavascriptInterface        publicvoidcallAndroid(final String str) {            System.out.print("!!!!"+str);            activity.setText(str);        }    }

This is my custom internal class, it has a callandroid method, note that the above must be written on @javascriptinterface, or some version of the SDK is wrong.
Then we look back at the JS file:

        <a href="#" onclick="window.GJNativeAPI.callAndroid(‘I am come from android.‘)">

Window is added when calling the native method, Gjnativeapi is our custom inner class, and Callandroid is the method we wrote, which completes the call.

Attention

If you write like this:

btn.setOnClickListener(new View.OnClickListener() {            @Override            publicvoidonClick(View v) {                //调用此语句,可以调用js里调用Android相关的方法,最终还是回到Android native                webView.loadUrl("javascript:window.GJNativeAPI.callAndroid(‘hello js‘)");            }});

You will find that you call in the native, back to the native, is the JS on a lap.

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Html5,js and Android native communication

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.