The use of jsbridge for the interaction between android and js

不言
Release: 2018-04-04 13:49:29
Original
1720 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 usecom.github.lzyzsd.jsbridge.BridgeWebViewinstead of nativeWebView
Place two moreButtonfor testing use

 
Copy after login

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

  Title



打印信息

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

webviewLoading 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

jsWebViewJavascriptBridgeRegister event monitoring and receive data