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