在android开发中,存在Android的原生Native层与JS网页混合开发的需求,此时可以使用WebViewJavascriptBridge框架进行桥接,实现JS与Native层相互通信。
下面对WebViewJavascriptBridge框架的实现流程做简单解释:
var wx = {
invoke: function(funcName, params, callBack) {
console.log('invoke: funcName=' + funcName + ", params=" + params + ", callBack=" + callBack);
var finalParams = {'funcName': funcName, 'orgparams': params};
window.WebViewJavascriptBridge.callHandler('submitFromWeb', finalParams, callBack);
},
};
//WebViewJavascriptBridge流程解释
//注册接口注释
//注册接口之后,当js层点击启动VPN时,
//1. js层:通知Native层有消息排队: 触发 BridgeWebViewClient.shouldOverrideUrlLoading(): url为 yy://__QUEUE_MESSAGE__/
//2. Native层:接收到通知(yy://__QUEUE_MESSAGE__/),通过 loadUrl("javascript:WebViewJavascriptBridge._fetchQueue();"), 想js层获取数据。
//3. js层: 组装js层需要发送的数据,再次触发 BridgeWebViewClient.shouldOverrideUrlLoading(),数据在url中,解析如下:
//eg: yy://return/_fetchQueue/[{"handlerName":"submitFromWeb","data":{"funcName":"ext_hulk_Start","orgparams":{"data":{"vpn_host":"xx.xx.xx.xx","vpn_port":"443","auth_server":"本地认证","auth_username":"zh","auth_password":"zh@1234","toast_enabled":"true"}}},"callbackId":"cb_10_1715422494134"}]
// yy://return/_fetchQueue/ 为js层native层发送数据的协议;
//data字段如下:
/*
[
{
"handlerName": "submitFromWeb",
"data": {
"funcName": "ext_hulk_Start",
"orgparams": {
"data": {
"vpn_host": "xx.xx.xx.xxx",
"vpn_port": "443",
"auth_server": "本地认证",
"username": "zh",
"password": "zh@1234",
"toast_enabled": "true"
}
}
},
"callbackId": "cb_10_1715422494134"
}
]
*/
//4. Native层的回调接口中处理data数据: 解析其中的 "handlerName","data","callbackId",
//注册 response的回调接口 responseFunction(CallBackFunction对象)传给业务层代码.
//5. APP层处理业务,处理完成之后,回调 responseFunction 回调接口的对象
//6. responseFunction 中新建一个Message对象,设置ResponseId为callbackId,设置ResponseData响应数据
//7 通过loadUrl接口加载url: "javascript:WebViewJavascriptBridge._handleMessageFromNative('%s');", %s为Message.toJson()数据:
/*
{
"responseData": "{\"vpn_errcode\":\"2560\",\"vpn_reason_code\":\"0x0FFFFFFF\",\"vpn_connected\":\"false\",\"vpn_state\":\"0\",\"vpn_errmsg\":\"网络故障\",\"err_msg\":\"ext_hulk_Start:ok\"}",
"responseId": "cb_11_1715423091997"
}
*/
//8. test.html页面接收到Native层返回的数据,处理js层业务
先描述流程,后续化流程书序图