接上篇
JsBridge
1.使用方法
1.1,java调用js指定方法,并有回调:
//java端的代码
webView.callHandler("functionInJs", param, new CallBackFunction() {
@Override
public void onCallBack(String data) {
//拿到H5端回调回来的参数
}
});
//H5端的代码
bridge.registerHandler("functionInJs", function(data, responseCallback) {
document.getElementById("show").innerHTML = ("data from Java: = " + data);
var responseData = "Javascript Says Right back aka!";
//将参数回调给native端
responseCallback(responseData);
});
java调用callHandler()的方法,必须要在H5中registerHandler(),而且方法名一样才能匹配到,
所以执行上可以看成 java—>js—>java。
1.2,js调用java
1,js发送消息给native端,并有回调
因为没有指定要处理的方法,则由java端的DefaultHandler拦截处理
//js代码
window.WebViewJavascriptBridge.send(
data
, function(responseData) {
//拿到H5端回调回来的参数
document.getElementById("show").innerHTML = "repsonseData from java, data = " + responseData
}
);
//java代码
//设置默认回调给JS的方法
webView.setDefaultHandler(new DefaultHandler());
public class DefaultHandler implements BridgeHandler {
String TAG = "DefaultHandler";
@Override
public void handler(String data, CallBackFunction function) {
if (function != null) {
//将参数回调到H5端
function.onCallBack("DefaultHandler response data"+ data);
}
}
}
js调用window.WebViewJavascriptBridge.send()的方法,会被java的DefaultHandler拦截
所以执行上可以看成 js—>java—>js。
2,js调用java指定方法,并有回调
//js代码
window.WebViewJavascriptBridge.callHandler(
'submitFromWeb'
, {'param': '中文测试'}
, function(responseData) {
//拿到H5端回调回来的参数
document.getElementById("show").innerHTML = "send get responseData from java, data = " + responseData
}
);
//java代码
webView.registerHandler("submitFromWeb", new BridgeHandler() {
@Override
public void handler(String data, CallBackFunction function) {
ToastUtil.showShort(ActivityDemo7.this,"hadler = submitFromWeb, data from web = " + data);
//将参数回调到H5端
function.onCallBack("submitFromWeb exe, response data 中文 from Java");
}
});
2.执行流程分析
2.1,java调用js指定方法,并有回调。
在java代码中,首先找到方法的入口,callHandler()。
webView.callHandler("functionInJs", params, new CallBackFunction() {
@Override
public void onCallBack(String data) {
}
});
进入callHandler()方法,调用了doSend()方法。
public void callHandler(String handlerName, String data, CallBackFunction callBack) {
doSend(handlerName, data, callBack);
}
看doSend()代码
/**
* native主动调用js代码
* @param handlerName js中的对应方法的名称
* @param data 要传递的参数
* @param responseCallback js代码执行后回调到这里的接口
*/
private void doSend(String handlerName, String data, CallBackFunction responseCallback) {
Message m = new Message();
if (!TextUtils.isEmpty(data)) {
m.setData(data);
}
if (responseCallback != null) {
String callbackStr = String.format(BridgeUtil.CALLBACK_ID_FORMAT, ++uniqueId + (BridgeUtil.UNDERLINE_STR + SystemClock.currentThreadTimeMillis()));
// doSend()中callbackStr:JAVA_CB_3_998
// doSend()中callbackStr:JAVA_CB_4_1022
Log.i("BridgeWebView","doSend()中callbackStr:"+callbackStr);
responseCallbacks.put(callbackStr, responseCallback);
m.setCallbackId(callbackStr);
}
if (!TextUtils.isEmpty(handlerName)) {
m.setHandlerName(handlerName);
}
queueMessage(m);
}
这里组装Message对象来保存调用方法的信息,假如存入了回调函数responseCallback ,则生成一个callbackStr 保存到本地的responseCallbacks中,继续进入queueMessage()方法
private void queueMessage(Message m) {
//假如native调用js代码,则startupMessage为null
if (startupMessage != null) {
startupMessage.add(m);
} else {
dispatchMessage(m);
}
}
假如native调用js代码,则startupMessage为null,所以进入到dispatchMessage()方法中
void dispatchMessage(Message m) {
String messageJson = m.toJson();
//escape special characters for json string
messageJson = messageJson.replaceAll("(\\\\)([^utrn])", "\\\\\\\\$1$2");
messageJson = messageJson.replaceAll("(?<=[^\\\\])(\")", "\\\\\"");
String javascriptCommand = String.format(BridgeUtil.JS_HANDLE_MESSAGE_FROM_JAVA, messageJson);
// dispatchMessage()中javascriptCommand:javascript:WebViewJavascriptBridge._handleMessageFromNative('{\"data\":\"hello\"}');
// dispatchMessage()中javascriptCommand:javascript:WebViewJavascriptBridge._handleMessageFromNative('{\"callbackId\":\"JAVA_CB_1_877\",\"data\":\"{\\\"location\\\":{\\\"address\\\":\\\"SDU\\\"},\\\"name\\\":\\\"大头鬼\\\"}\",\"handlerName\":\"functionInJs\"}');
Log.i("BridgeWebView","dispatchMessage()中javascriptCommand:"+javascriptCommand);
if (Thread.currentThread() == Looper.getMainLooper().getThread()) {
this.loadUrl(javascriptCommand);
}
}
这段代码就是native调用js代码的关键,方法中先从message对象中解析json数据将信息解析,拼接出类似
javascript:WebViewJavascriptBridge._handleMessageFromNative('{\"callbackId\":\"JAVA_CB_1_877\",\"data\":\"{\\\"location\\\":{\\\"address\\\":\\\"SDU\\\"},\\\"name\\\":\\\"大头鬼\\\"}\",\"handlerName\":\"functionInJs\"}
的代码,再通过
if (Thread.currentThread() == Looper.getMainLooper().getThread()) {
this.loadUrl(javascriptCommand);
}
在主线程中webView.loadUrl(),所以其实java调用js的核心还是webView.loadUrl()这个方法,但是JsBridge库对其进行了封装,这样java就不能调用js中的任意代码(本来webView.loadUrl()这个方法只要传入拼接对的js代码,就能调用该js代码)。
追踪到js的WebViewJavascriptBridge._handleMessageFromNative代码
function _handleMessageFromNative(messageJSON) {
console.log(messageJSON);
if (receiveMessageQueue && receiveMessageQueue.length > 0) {
receiveMessageQueue.push(messageJSON);
} else {
_dispatchMessageFromNative(messageJSON);
}
}
这里还没搞懂receiveMessageQueue 的作用是什么,只知道调用了_dispatchMessageFromNative()方法,所以继续进入方法
//按照messageJson进行事件的调用,假如有callback,则调用完之后callback
function _dispatchMessageFromNative(messageJSON) {
setTimeout(function() {
//解析出callbackId(假如存在回调)和参数,
var message = JSON.parse(messageJSON);
var responseCallback;
//java call finished, now need to call js callback function
//假如存在responseId,则回调完成时去除callId
if (message.responseId) {
responseCallback = responseCallbacks[message.responseId];
if (!responseCallback) {
return;
}
responseCallback(message.responseData);
delete responseCallbacks[message.responseId];
} else {
//直接发送
if (message.callbackId) {
var callbackResponseId = message.callbackId;
responseCallback = function(responseData) {
//js回调给java
_doSend({
responseId: callbackResponseId,
responseData: responseData
});
};
}
var handler = WebViewJavascriptBridge._messageHandler;
if (message.handlerName) {
handler = messageHandlers[message.handlerName];
}
//查找指定handler
try {
handler(message.data, responseCallback);
} catch (exception) {
if (typeof console != 'undefined') {
console.log("WebViewJavascriptBridge: WARNING: javascript handler threw.", message, exception);
}
}
}
});
}
这段代码中,因为是java主动调用js,所以message.responseId为null,直接走else,先组装回调函数responseCallBack()
if (message.callbackId) {
var callbackResponseId = message.callbackId;
responseCallback = function(responseData) {
//js回调给java
_doSend({
responseId: callbackResponseId,
responseData: responseData
});
};
}
接着根据handler = messageHandlers[message.handlerName];
拿到handler
//查找指定handler
try {
handler(message.data, responseCallback);
} catch (exception) {
if (typeof console != 'undefined') {
console.log("WebViewJavascriptBridge: WARNING: javascript handler threw.", message, exception);
}
}
最后就是调用方法,追踪到注册的方法
connectWebViewJavascriptBridge(function(bridge) {
......
//为js注册Handler,
bridge.registerHandler("functionInJs", function(data, responseCallback) {
document.getElementById("show").innerHTML = ("data from Java: = " + data);
var responseData = "Javascript Says Right back aka!";
responseCallback(responseData);
});
})
最后调用了responseCallback(responseData),responseCallback()在上面已经组装成功,就是调用了_doSend()这个方法
//sendMessage add message, 触发native处理 sendMessage
//将数据返回到native,回调到native时就是调用这个方法
function _doSend(message, responseCallback) {
if (responseCallback) {
var callbackId = 'cb_' + (uniqueId++) + '_' + new Date().getTime();
responseCallbacks[callbackId] = responseCallback;
message.callbackId = callbackId;
}
sendMessageQueue.push(message);
messagingIframe.src = CUSTOM_PROTOCOL_SCHEME + '://' + QUEUE_HAS_MESSAGE;
}
这里涉及到一些前端的知识,利用iframe.src的变化,触发了BridgeWebViewClient的shouldOverrideUrlLoading将数据返回到native端,这样就实现了js回调到native了。
所以总体上流程是:
3,js调用java指定方法,并有回调
找到js代码的入口,window.WebViewJavascriptBridge.callHandler(...)
//function的responseData是回调的值
//js调用特定的java方法
window.WebViewJavascriptBridge.callHandler(
'submitFromWeb'
, {'param': '中文测试'}
, function(responseData) {
document.getElementById("show").innerHTML = "send get responseData from java, data = " + responseData
}
);
进入callHandler()方法,也是调用了_doSend()方法,将数据传递到native
function callHandler(handlerName, data, responseCallback) {
_doSend({
handlerName: handlerName,
data: data
}, responseCallback);
}
与上面js调用java流程中的_doSend()一样,通过改变iframe.src触发native的shouldOverrideUrlLoading()方法
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
try {
url = URLDecoder.decode(url, "UTF-8");
Log.i("BridgeWebViewClient","查看触发的schema:"+url);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
if (url.startsWith(BridgeUtil.YY_RETURN_DATA)) { // 如果是返回数据
webView.handlerReturnData(url);
return true;
} else if (url.startsWith(BridgeUtil.YY_OVERRIDE_SCHEMA)) { //
webView.flushMessageQueue();
return true;
} else {
return super.shouldOverrideUrlLoading(view, url);
}
}
接着走的是webView.flushMessageQueue()这个方法
void flushMessageQueue() {
if (Thread.currentThread() == Looper.getMainLooper().getThread()) {
loadUrl(BridgeUtil.JS_FETCH_QUEUE_FROM_JAVA, new CallBackFunction() {
@Override
public void onCallBack(String data) {
// deserializeMessage
List list = null;
try {
list = Message.toArrayList(data);
} catch (Exception e) {
e.printStackTrace();
return;
}
if (list == null || list.size() == 0) {
return;
}
for (int i = 0; i < list.size(); i++) {
Message m = list.get(i);
String responseId = m.getResponseId();
// 是否是response
if (!TextUtils.isEmpty(responseId)) {
CallBackFunction function = responseCallbacks.get(responseId);
String responseData = m.getResponseData();
function.onCallBack(responseData);
responseCallbacks.remove(responseId);
} else {
CallBackFunction responseFunction = null;
// if had callbackId
final String callbackId = m.getCallbackId();
if (!TextUtils.isEmpty(callbackId)) {
responseFunction = new CallBackFunction() {
@Override
public void onCallBack(String data) {
Message responseMsg = new Message();
responseMsg.setResponseId(callbackId);
responseMsg.setResponseData(data);
queueMessage(responseMsg);
}
};
} else {
responseFunction = new CallBackFunction() {
@Override
public void onCallBack(String data) {
// do nothing
}
};
}
BridgeHandler handler;
if (!TextUtils.isEmpty(m.getHandlerName())) {
handler = messageHandlers.get(m.getHandlerName());
} else {
handler = defaultHandler;
}
if (handler != null) {
handler.handler(m.getData(), responseFunction);
}
}
}
}
});
}
}
这个方法是在BridgeWebView中定义的,做的是在主线程中调用loadUrl(javascript:WebViewJavascriptBridge._fetchQueue(), new CallBackFunction());
这个方法。
所以,追踪到js中的_fetchQueue()中
// 提供给native调用,该函数作用:获取sendMessageQueue返回给native,由于android不能直接获取返回的内容,所以使用url shouldOverrideUrlLoading 的方式返回内容
function _fetchQueue() {
var messageQueueString = JSON.stringify(sendMessageQueue);
sendMessageQueue = [];
//android can't read directly the return data, so we can reload iframe src to communicate with java
messagingIframe.src = CUSTOM_PROTOCOL_SCHEME + '://return/_fetchQueue/' + encodeURIComponent(messageQueueString);
}
这里将js传递的参数拼接入Url中,传递到native,而相应的shouldOverrideUrlLoading 中调用handlerReturnData()这个方法
/**
* 处理返回的数据
*
* @param url
*/
void handlerReturnData(String url) {
String functionName = BridgeUtil.getFunctionFromReturnUrl(url);
CallBackFunction f = responseCallbacks.get(functionName);
String data = BridgeUtil.getDataFromReturnUrl(url);
if (f != null) {
f.onCallBack(data);
responseCallbacks.remove(functionName);
return;
}
}
这里就是调用native本地方法
if (f != null) {
f.onCallBack(data);
}
所以总体上流程是
留意整个流程,js的第一次_doSend()只不过是通知native调用javascript:WebViewJavascriptBridge._fetchQueue();来取消息,包括要调用的方法,参数,回调的id。所以其实真正调用native方法的是js层的_fetchQueue()。