Home > Web Front-end > JS Tutorial > body text

The use of jsbridge for the interaction between android and js

不言
Release: 2018-04-04 13:49:29
Original
1845 people have browsed it


As we all know, some functions of the app may use H5 development, which will inevitably encounter mutual calls between java and js. Android uses WebViewJavascriptBridge to realize the interaction between js and java. Here is an introduction Next, use the JsBridge third-party library.
github portal: https://github.com/lzyzsd/JsBridge

Simple analysis

Java and js call each other as follows:
java sends data to js, ​​and js receives it And pass it back to java
Similarly, js sends data to java, java receives and passes it back to js
At the same time, both processes have "default reception" and "specified reception"
The approximate call flow chart is as follows :

Dependencies

project build.gradle

repositories {
    // ...
    maven { url "https://jitpack.io" }
}
Copy after login

app build.gradle

dependencies {
    compile 'com.github.lzyzsd:jsbridge:1.0.4'}
Copy after login

xml Directly use com.github.lzyzsd.jsbridge.BridgeWebView instead of native WebView
Place two more Button for testing use

<?xml version="1.0" encoding="utf-8"?><android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Button        android:id="@+id/java_to_js_default"
        android:layout_width="180dp"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:text="java发送给js默认接收"
        app:layout_constraintTop_toBottomOf="@+id/nav_bar" />

    <Button        android:id="@+id/java_to_js_spec"
        android:layout_width="180dp"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:text="java发送给js指定接收"
        app:layout_constraintTop_toBottomOf="@+id/java_to_js_default" />

    <com.github.lzyzsd.jsbridge.BridgeWebView        android:id="@+id/webView"
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/java_to_js_spec" /></android.support.constraint.ConstraintLayout>
Copy after login

Simply place two buttons in the html file to send data and provide printing information at the same time

<html lang="en"><head>
    <meta charset="UTF-8">
    <title>Title</title></head><body><p>
    <button onClick="jsToJavaDefault()">js发送给java默认接收</button></p><br/><p>
    <button onClick="jsToJavaSpec()">js发送给java指定接收</button></p><br/><p id="show">打印信息</p></body></html>
Copy after login

Here I am running a simple django project locally and set up a service for use

webView.loadUrl("http://10.0.0.142:8000/cake/jsbridge");
Copy after login

webview Loading page

java sends data to js

buttonRegister to listen

javaToJsDefault.setOnClickListener(this);
javaToJsSpec.setOnClickListener(this);
Copy after login

Button click event, java passes Data to js

    //java传递数据给js
    @Override
    public void onClick(View v) {        switch (v.getId()) {            case R.id.java_to_js_default:                //默认接收
                webView.send("发送数据给js默认接收", new CallBackFunction() {                    @Override
                    public void onCallBack(String data) { //处理js回传的数据
                        Toast.makeText(WebTestActivity.this, data, Toast.LENGTH_LONG).show();
                    }
                });                break;            case R.id.java_to_js_spec:                //指定接收参数 functionInJs
                webView.callHandler("functionInJs", "发送数据给js指定接收", new CallBackFunction() {                    @Override
                    public void onCallBack(String data) { //处理js回传的数据
                        Toast.makeText(WebTestActivity.this, data, Toast.LENGTH_LONG).show();
                    }
                });                break;            default:                break;
        }
    }
Copy after login

js WebViewJavascriptBridgeRegister event monitoring and receive data

<script>

       //注册事件监听,初始化
       function setupWebViewJavascriptBridge(callback) {
           if (window.WebViewJavascriptBridge) {
               callback(WebViewJavascriptBridge)
           } else {
               document.addEventListener(                   &#39;WebViewJavascriptBridgeReady&#39;
                   , function() {
                       callback(WebViewJavascriptBridge)
                   },                   false
               );
           }
       }       //回调函数,接收java发送来的数据
       setupWebViewJavascriptBridge(function(bridge) {
           //默认接收
           bridge.init(function(message, responseCallback) {
               document.getElementById("show").innerHTML = &#39;默认接收到Java的数据: &#39; + message;               var responseData = &#39;js默认接收完毕,并回传数据给java&#39;;
               responseCallback(responseData); //回传数据给java
           });           //指定接收,参数functionInJs 与java保持一致
           bridge.registerHandler("functionInJs", function(data, responseCallback) {
               document.getElementById("show").innerHTML = &#39;指定接收到Java的数据: &#39; + data;               var responseData = &#39;js指定接收完毕,并回传数据给java&#39;;
               responseCallback(responseData); //回传数据给java
           });
       })

<script>
Copy after login

java is sent to js and is received by default

java Send to js to specify the reception

js sends data to java

js button click event. At the same time, the above WebViewJavascriptBridge registration listening callback function## is required. #

    //js传递数据给java
    function jsToJavaDefault() {
       var data = &#39;发送数据给java默认接收&#39;;
       window.WebViewJavascriptBridge.send(
           data
           , function(responseData) { //处理java回传的数据
              document.getElementById("show").innerHTML = responseData;
           }
       );
   }   function jsToJavaSpec() {
       var data=&#39;发送数据给java指定接收&#39;;
       window.WebViewJavascriptBridge.callHandler(           &#39;submitFromWeb&#39; //指定接收参数 submitFromWeb与java一致
           ,data
           , function(responseData) { //处理java回传的数据
              document.getElementById("show").innerHTML = responseData;
           }
       );
   }
Copy after login

java Monitor and receive data

        //默认接收
        webView.setDefaultHandler(new BridgeHandler() {            @Override
            public void handler(String data, CallBackFunction function) {
                String msg = "默认接收到js的数据:" + data;
                Toast.makeText(WebTestActivity.this, msg, Toast.LENGTH_LONG).show();

                function.onCallBack("java默认接收完毕,并回传数据给js"); //回传数据给js
            }
        });        //指定接收 submitFromWeb 与js保持一致
        webView.registerHandler("submitFromWeb", new BridgeHandler() {            @Override
            public void handler(String data, CallBackFunction function) {
                String msg = "指定接收到js的数据:" + data;
                Toast.makeText(WebTestActivity.this, msg, Toast.LENGTH_LONG).show();

                function.onCallBack("java指定接收完毕,并回传数据给js"); //回传数据给js
            }
        });
Copy after login
js is sent to java for default reception


js is sent to java for specified reception


At this point, the usage process of jsBridge is completed.

Related recommendations:

WeChat browser built-in JavaScript object WeixinJSBridge usage examples_javascript skills


The above is the detailed content of The use of jsbridge for the interaction between android and js. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template