【知识】【安卓】JsBridge

学习一个 H5 与安卓原生的交互方法 JsBridge

Js 调 Java

Java 创建 Handler

1
2
3
4
5
6
7
webView.registerHandler("hello", new BridgeHandler() {
@Override
public void handler(String data, CallBackFunction function) {
CusToast.showToast("hello:" + data);
function.onCallBack("hi there");
}
});

Js 指定 handler

1
2
3
4
5
6
7
8
9
10
11
function test() {
var str = "world";

//send message to native
var data = {str};
window.WebViewJavascriptBridge.callHandler('hello'
, {'param': data}
, function(responseData) {
document.getElementById("show").innerHTML = responseData;
});
}

另一种不需要指定 Hanlder 的处理模式
Java 创建默认 Handler

1
2
3
4
5
6
7
webView.setDefaultHandler(new BridgeHandler() {
@Override
public void handler(String data, CallBackFunction function) {
CusToast.showToast("receive data:" + data);
function.onCallBack("okay");
}
});

Js 发消息

1
2
3
4
5
6
7
8
9
function test() {
var data = "";
window.WebViewJavascriptBridge.send(
data
, function(responseData) {
document.getElementById("show").innerHTML = "repsonseData from java, data = " + responseData
}
);
}

Java 调 Js

Js 创建 Hanlder

1
2
3
4
5
6
7
8
9
connectWebViewJavascriptBridge(function(bridge) {
bridge.registerHandler("Jsfunc", function(data, responseCallback) {
document.getElementById("init").innerHTML = ("data: " + data);
if (responseCallback) {
var responseData = "okay";
responseCallback(responseData);
}
});
})

Java 指定 Handler

1
2
3
4
5
6
7
8
9
10
11
12
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
webView.callHandler("Jsfunc", "test data", new CallBackFunction() {

@Override
public void onCallBack(String data) {
CusToast.showToast("js resp: " + data);
}
});
}
});

同样有不指定 Hanlder 的模式
Js 创建

1
2
3
4
5
6
7
8
connectWebViewJavascriptBridge(function(bridge) {
bridge.init(function(message, responseCallback) {
console.log('message:', message);
var data = "got it";
console.log('JS resp: ', data);
responseCallback(data);
});
})

Java 层

1
2
3
4
5
6
webView.send("message from Java", new CallBackFunction() {
@Override
public void onCallBack(String data) {
CusToast.showToast("Js resp: " + data);
}
});