android native and H5 interaction

Keywords: Android Javascript Java xml

Recently, a hybrid APP of Android native H5 was developed on the left. Before that, we haven't summarized the interaction methods between Android native and H5. Here's a summary:

1. hybrid communication is mainly the communication between the front-end JS and our Android. This is the most basic communication mode between JS and Java:
Here we are divided into four parts:
(1) , js calls android native code (no parameters passed)

   (2) , js calls android native code (passing parameters)

   (3) , android native calling JS code (no parameters passed)

   (4) , android native calling JS code (passing parameters)


 OK, let's create a project first:

Create a folder assets under the main folder of the project, and put the written H5 page into the folder. The H5 page code is as follows:
  <pre name="code" class="html"><!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" />  
    <title>This is a H5 page</title>  
</head>  
  
<body>  
<p id="ptext">Click key 0 to execute android Medium public void click0(){} Method</p>  
<Button id="buttonId0" class="buttonClass" onclick="javascript:button.click0()">Key 0</Button>  
<p>Click button 1 to execute android Medium public void click0(String data1,String data2){}Method</p>  
<Button id="buttonId1" class="buttonClass" onclick="javascript:button.click0('Parameter 1','Parameter 2')">Key 1</Button>  
  
<script>  
        function setRed(){  
        //This method sets the background color of the element with id of ptext to red  
        var a = document.getElementById('ptext');  
        a.style.backgroundColor="#F00";  
    }  
    function setColor(color,text){  
        //This method sets the background color of the element with id as ptext to the specified color  
        //Set the content of the element with id as ptext to text  
        var a = document.getElementById('ptext');  
        a.style.backgroundColor=color;  
        a.innerHTML = text;  
    }  
    </script>  
</body>  

On the top is a simple H5 page, which contains two buttons. Click the button to trigger the android native method. There are two JS methods, including two, which are mainly used to call android native.

Go back to activity main.xml, and the layout is as follows:

<?xml version="1.0" encoding="utf-8"?>  
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
    xmlns:tools="http://schemas.android.com/tools"  
    android:layout_width="match_parent"  
    android:layout_height="match_parent"  
    tools:context="manyizilin.com.androidh5.MainActivity">  
  
    <WebView android:id="@+id/webview"  
        android:layout_height="match_parent"  
        android:layout_width="match_parent"  
        />  
    <LinearLayout android:layout_width="match_parent"  
        android:layout_height="wrap_content"  
        android:layout_alignParentBottom="true"  
        android:orientation="horizontal">  
        <Button android:id="@+id/red"  
            android:layout_height="wrap_content"  
            android:layout_width="wrap_content"  
            android:layout_weight="1"  
            android:text="The background turns red"/>  
        <Button android:id="@+id/color"  
            android:layout_height="wrap_content"  
            android:layout_width="wrap_content"  
            android:layout_weight="1"  
            android:text="Background color can be customized"/>  
    </LinearLayout>  
</RelativeLayout>  

It mainly includes a WebView control and two buttons. Clicking the button can trigger the JS method in the upper H5 page
Finally, take a look at the code of MainActivity:

public class MainActivity extends AppCompatActivity implements View.OnClickListener{  
  
    private WebView webView;  
    private Button redButton,colorButton;  
    @Override  
    protected void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
        setContentView(R.layout.activity_main);  
        webView = (WebView)findViewById(R.id.webview);  
        redButton = (Button)findViewById(R.id.red);  
        colorButton = (Button)findViewById(R.id.color);  
        redButton.setOnClickListener(this);  
        colorButton.setOnClickListener(this);  
        initWebView();  
        webView.loadUrl("file:///android_asset/android&h5Text0.html"); //Load H5 page in assets file  
    }  
  
    /** 
     *Initialize WebView 
     */  
  @SuppressLint("JavascriptInterface")  //Add this field  
 private void initWebView(){  
        WebSettings settings =  webView.getSettings();  
        settings.setJavaScriptEnabled(true);  //Set to run using JS  
        ButtonClick click = new ButtonClick();  
        //Add JS interaction event here, so H5 can call the native code  
        webView.addJavascriptInterface(click,click.toString());  
    }  
  
    @Override  
    public void onClick(View v) {  
        switch (v.getId()){  
            case R.id.red:  //Calling parameterless methods in JS  
                webView.loadUrl("javascript:setRed()");  
                break;  
            case R.id.color://call JS Parametric method in  
                webView.loadUrl("javascript:setColor('#00f ','This is the trigger event of android native calling JS code')“);  
                break;  
        }  
    }  
  
    /** 
     * H5 Page button click trigger event 
     */  
    class ButtonClick{  
  
        //This is the trigger event for button.click0()  
        //H5 call method: javascript:button.click0()  
        @JavascriptInterface  
        public void click0(){  
           show("title","");  
        }  
  
        //This is the trigger event of button.click0(), which can pass the parameter  
        //H5 calling method: javascript:button.click0('parameter 1 ','parameter 2')  
        @JavascriptInterface  
        public void click0(String data1,String data2){  
            show(data1,data2);  
        }  
  
  
        @JavascriptInterface  //Must be added to mark that the name of this class is button  
        public String toString(){  
            return "button";  
        }  
  
        private void show(String title,String data){  
            new AlertDialog.Builder(getWindow().getContext())  
                    .setTitle(title)  
                    .setMessage(data)  
                    .setPositiveButton("Determine",null)  
                    .create().show();  
        }  
    }  
}  

OK, that's the code above. Let's explain it in detail:

First, we get a WebView, initialize WebView. To run JS script in WebView, we must set:

WebSettings settings =  webView.getSettings(;  
settings.setJavaScriptEnabled(true);  //Set to run using JSeang  

Load the H5 page in assets:

webView.loadUrl("file:///android_asset/android&h5Text0.html"); //Load H5 page in assets file

Next, write a class for JS calls;

 Remember to write the toString() method, and the result returned is consistent with the class name in the method called in JS:

For example: in this example, JS calls are native to JavaScript: button.click0(); note that the return value of this button is the same as that of the toSring() method of the response class in Java.

@JavascriptInterface 
         public String toString(){             return "button";         }

JavaScript:button.click0(); the method names of click0 and java response class trigger methods are consistent. Method is public.

**  
     * H5 Page button click trigger event  
     */  
    class ButtonClick{  
  
        //This is the trigger event for button.click0()  
        //H5 call method: javascript:button.click0()  
        @JavascriptInterface  
        public void click0(){  
           show("title","");  
        }  
  
        //This is the trigger event of button.click0(), which can pass the parameter  
        //H5 calling method: javascript:button.click0('parameter 1 ','parameter 2')  
        @JavascriptInterface  
        public void click0(String data1,String data2){  
            show(data1,data2);  
        }  
  
  
        @JavascriptInterface  //It must be added to mark that the name of this class is button / / it does not need to be added before android 4.2. It needs to be added after android 4.2  
        public String toString(){  
            return "<strong>button</strong>";  
        }  
  
        private void show(String title,String data){  
            new AlertDialog.Builder(getWindow().getContext())  
                    .setTitle(title)  
                    .setMessage(data)  
                    .setPositiveButton("Determine",null)  
                    .create().show();  
        }  
    }  

All right, we're almost ready

(1) , js calls android native code (parameters are not passed) / (2), js calls android native code (parameters are passed)
Then we inject an interface written by ourselves through WebView's addJavascriptInterface method.

 ButtonClick click = new ButtonClick();   
  //Add JS interaction event here, so H5 can call the native code  
  webView.addJavascriptInterface(click,click.toString());  

Here's a description of the addJavascriptInterface method. The first parameter is the trigger object, and the second parameter is the flag of the object. You need to add the following code inside the class so that JS can identify the internal method of the class:

@JavascriptInterface  //@JavaScript interface must be added to mark that the name of this class is button / / it does not need to be added before android 4.2, and it needs to be added after android 4.2  
  public String toString(){  
      return "button";  
  }  

Now click the key 0 in the H5 page to trigger the click0() method in the ButtonClick class. Click the key 1 to trigger the click0(String data1,String data2) method in the ButtonClick class

(3) , android native calling JS code (no parameters passed)

   After loading the H5 page, call webView.loadUrl("javascript:setRed()"); then you can call the JS method setRed() in the page

(4) , android native calling JS code (passing parameters)

After loading the H5 page, call
webView.loadUrl("javascript:setColor('ා00f','This is the trigger event of android calling JS code natively ')";
Then you can call the JS method setColor(color,text) in the page

--------
Copyright notice: This is the original article of CSDN blogger "ManYiZilin", following CC 4.0 BY-SA copyright agreement. Please attach the original source link and this notice for reprint.
Original link: https://blog.csdn.net/ManYiZilin/article/details/69258032

Published 24 original articles, won praise 2, visited 10000+
Private letter follow

Posted by fewtrem on Tue, 14 Jan 2020 20:32:01 -0800