* * In Android Development, more and more commercial projects are using Android native controls to mix with WebView, not just to show a webview, and sometimes to interact with JavaScript in the HTML with native Java code. , Android has also done a good job of packaging the interaction, so it is easy to implement for example: Click on the page of the button Android call the native dialog box, click the phone number in the page Call Android Dial-up app. This article shows you how to achieve Android and html+js interaction.
The main function points of this article:
1, WebView How to load H5 page
2. How Android calls methods in H5
3, H5 How to call the method in Android
1, WebView How to load H5 page
We all know that the HTML page is loaded via WebView in Android, and it differs depending on where the HTML file is located:
*//加载assets文件夹下的test.html页面,文件1**mWebView.loadUrl("file:///android_asset/test.html");**//加载网页**mWebView.loadUrl("http://www.baidu.com");*
Figure 1: Loading the test.html file in the local assets
2. How Android calls methods in H5**
if you want to invoke the JS method then you have to let WebView support
*WebSettings webSettings = mWebView.getSettings();**//设置为可调用js方法**webSettings.setJavaScriptEnabled(true);*
**
How to invoke?
Android calls the method in H5, in fact very simple, directly call on it, do not need extra action.
① call method without parameter return value in H5 * * *
You can call Mwebview.loadurl ("Javascript:show ()") directly, and Figure 2 is the show () method in H5. *
**mWebView.loadUrl("JavaScript:show()");**
Figure 2:android Calling a method in H5 with no return value for parameters in H5
**
② call method with return value in H5 * * *
You can call the Mwebview.evaluatejavascript () method, which is only available on Android 4.4 or later, and Figure 3 is the way Android calls the return value in H5.
*mWebView.evaluateJavascript("sum(1,2)",new ValueCallback() { ** @Override** public void on ReceiveValue(String value) { ** Log.e(TAG,"onReceiveValue value=" + value); ** } ** });*
Figure 3: How Android calls H5 with return values
**
③ calling a method with parameters in H5 * * *
When calling a method with parameters in H5, it is bound to pass in a string that is enclosed in single quotation marks when the fixed string is passed in, and when the variable name is passed in, it is necessary to use the escape character (here I also spend half an hour to understand, hehe). Two case codes, respectively, are posted below, apply 4.
mWebView.loadUrl("javascript:alertMessage(‘哈哈‘)");
*String content="9880";*mWebView.loadUrl( "javascript:alertMessage(\" " +content+ "\")" );
Figure 4:android Calling a method with parameters in H5
3, H5 How to call the method in Android
*H5 calls the method in Android, relatively complex, the two sides specific actions are as follows:
What does Android need to do????? ***
To put it bluntly is to create a new class, which writes the method that provides the H5 operation, and specifies the alias. Here I created a new class for Jsinteration, the method is back (), the specified alias is Android. Paste first, post code. *
Figure 4:h5 Call Android method, Android needs the action
Above Android 4.2 can be directly declared using @javascriptinterface annotations, the following is in a local Java method
public class JsInteration { @JavascriptInterface public String back() { return "hello world"; }}
After you define this method, call the Mwebview.addjavascriptinterface () method:
mWebView.addJavascriptInterface(newJsInteration(),"android");
How to invoke it in H5?
The call format is window. Alias. The method name in Android (parameter Values), in this example we used an alias of Android, the method name is back (). First, post-paste the code.
Figure 4:h5 Call Android method, Android needs the action
**
The H5 code is as follows: * *
*function s() {* var result=window.android.back(); document.getElementById("p").innerHTML=result;}
This is one of the ways that Android calls the H5 method and how H5 calls the Android method to implement the interaction. The complete code is given below:
**
Mainactivity Code: * * *
Package Com.e_valmont.javaandjsinteractivedemo;Import Android.annotation.SuppressLint;Import Android.annotation.TargetApi;Import Android.os.Build;Import android.support.v7.app.AppCompatActivity;Import Android.os.Bundle;Import Android.util.Log;Import Android.view.View;Import Android.webkit.JavascriptInterface;Import Android.webkit.ValueCallback;Import android.webkit.WebChromeClient;Import android.webkit.WebSettings;Import Android.webkit.WebView;Import android.webkit.WebViewClient;Import Android.widget.Toast;PublicClassMainactivityExtendsappcompatactivity{PrivateStaticFinal String TAG ="Mainactivity";Private WebView Mwebview;@SuppressLint ("Javascriptinterface")@OverrideProtectedvoidOnCreate(Bundle savedinstancestate) {Super.oncreate (savedinstancestate); Setcontentview (R.layout.activity_main); Mwebview = (WebView) Findviewbyid (R.id.webview); Mwebview.loadurl ("File:///android_asset/js_java_interaction.html");Load the js_java_interaction.html file below the local assetMwebview.loadurl ("https://www.baidu.com/");//load local assets The js_java_interaction.html file below websettings websettings = Mwebview.getsettings (); Websettings.setjavascriptenabled (true);Turn on JS support/** * Open the JS interface to the H5 call, Parameter 1 is the local class name, Parameter 2 is an alias, H5 with window. Alias. The method name in the class name to invoke the contents of the method, for example: Window.android.back (); * * */Mwebview.addjavascriptinterface (New Jsinteration (),"Android"); Mwebview.setwebviewclient (New Webviewclient ()); Mwebview.setwebchromeclient (New Webchromeclient ()); }/** * Write a class yourself, which is the method provided to H5 access * */PublicClassjsinteration {@JavascriptInterfaceBe sure to write, otherwise H5 can't get this methodPublic StringBack() {Return"I am the method return value in Java"; } }Click the button to access the method of return value in H5@TargetApi (build.version_codes. KITKAT)PublicvoidOnClick(View v) {LOG.E ("TAG","OnClick:");Mwebview.loadurl ("Javascript:show ()");//direct access to H5 without the return value, show () is the method in the H5A fixed string can be directly enclosed in single quotation marks (Mwebview.loadurl)."Javascript:alertmessage (' haha ')");To access the H5 parameter method, Alertmessage (message) is the method in H5//When entering and exiting variable names, you need to separate String content="9880" with escape characters; Mwebview.loadurl ("javascript:alertmessage (\" "+content+ " \")" ); //android Call has a return value JS method, Android 4.4 or more to use this method Mwebview.evaluatejavascript ("sum", new valuecallback< String> () { @Override public void onreceivevalue(String value) {log.d (TAG, "JS returns the result =" + Value); Toast.maketext (mainactivity. This,"JS returns the result =" + Value,toast.length_long). Show (); } }); }}
Activiy_main.xml Code:
<?xml version="1.0" encoding="Utf-8"?><LinearLayoutXmlns:android="Http://schemas.android.com/apk/res/android"Android:layout_width="Fill_parent"android:layout_height="Fill_parent"android:orientation="Vertical" ><webview android:id= "@+id/webview" android:layout_width= "fill_parent" android:layout_height= "fill_parent" android:layout_weight= "9"/> <button android:layout_width= "match_parent" Android:layout_height= "wrap_content" android:onClick= "OnClick" android:text= "click Invoke JS Method"/>< Span class= "Hljs-tag" ></LINEARLAYOUT>
Js_java_interaction.html Code:
<Head><!--the Chinese page loaded from the Assert is garbled, the solution is to specify the encoding for the HTML--<Metahttp-equiv="Content-type"Content="text/html;charset=gb2312" ><Title></Title></Head><Body> This is an HTML page<Br/><buttononclick="s ()" > click Invoke Local Method</Button><Ahref="File:///android_asset/js_java_interaction.html" > click to jump to the native page</A><PId="P" ></P><ScriptType="Text/javascript" > Methods of having a parameter return valuefunctionSumb) {<!--gygguuuiu-->return a+b; }Methods with no return value for parametersfunctionAlertmessage (Message) {alert (message);}Method of no parameter return valuefunctionshow (//show Hello World document.getelementbyid ( "P"). Innerhtml=function s ( //call native method, Android is the contracted alias; back () is the native method var result=window.android.back (); //will return the results displayed on the control with ID p document.getelementbyid (" P "). Innerhtml=result; } </script> </ body></HTML>
**
Precautions: * * *
1, when you write HTML files, may appear garbled, we need to specify the format
Display garbled for HTML, action to be performed
2, when H5 call our method, we need to pass the specified alias to H5 (remember must not be wrong), and we have to do in their own method H5 want to do.
We're going to have to pass it on to H5.
3, to H5 call method must add @javascriptinterface, otherwise H5 can't tune our method
@JavascriptInterface must add
4, the call JS has the parameter has the return value function, only Android 4.4 above can use the Webview.evaluatejavascript method to get the return value directly, when the version is below 4.4, the common idea is the Java calls the JS method, the JS method executes, Call the Java code again to return the value.
①.java Calling JS code
String call = "javascript:sumToJava(1,2)";webView.loadUrl(call);
The ②.js function processes and returns the result by calling the Java method
function sumToJava(number1, number2){ window.control.onSumResult(number1 + number2)}
③.java get the return value of the JS function in the callback method
@JavascriptInterfacepublic void onSumResult(int result) { Log.i(LOGTAG, "onSumResult result=" + result);}
5, load the local assets H5 interface, to write android_asset, not assets, otherwise load not
Note format
Reference article:The interaction between Android and H5
Code Guest _yang
Links: Https://www.jianshu.com/p/0b986d6e2e17
Source: Pinterest
Copyright belongs to the author. Commercial reprint please contact the author for authorization, non-commercial reprint please specify the source.
Android Hybrid development-native Java and H5 interaction to ensure you understand!