Android集成JsBridge
Github:https://github.com/lzyzsd/JsBridge
依赖
repositories {
maven { url "https://jitpack.io" }
}
dependencies {
api 'com.github.lzyzsd:jsbridge:1.0.4'
}
布局文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<com.github.lzyzsd.jsbridge.BridgeWebView
android:id="@+id/bridge_web_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</LinearLayout>
Java实现
public class JsBridgeActivity extends AppCompatActivity {
private BridgeWebView mBridgeWebView;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mian);
mBridgeWebView = findViewById(R.id.bridge_web_view);
mBridgeWebView.loadUrl("file:///android_asset/demo.html");
mBridgeWebView.registerHandler("getHomePage", new BridgeHandler() {
@Override
public void handler(String data, CallBackFunction function) {
NLog.i(Constants.TAG, "JsBridgeActivity.getHomePage: " + data);
function.onCallBack("http://www.appblog.cn");
}
});
}
}
JS代码
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta http-equiv="content-type" content="text/html;charset=utf-8"/>
<title>Android与JS交互测试</title>
</head>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<body style="margin: 20px;">
<div class="form-group">
<textarea id="show" class="form-control" rows="6"></textarea>
</div>
<div class="form-group">
<input type="button" class="form-control btn btn-default" style="background-color:#30B7EB;" value="获取主页信息" onclick="callNativeHomePage();" />
</div>
</body>
<script>
function callNativeHomePage() {
//call native method
window.WebViewJavascriptBridge.callHandler(
'getHomePage'
, {'param': 'value'}
, function(responseData) {
document.getElementById("show").innerHTML = responseData
}
);
}
function connectWebViewJavascriptBridge(callback) {
if (window.WebViewJavascriptBridge) {
callback(WebViewJavascriptBridge)
} else {
document.addEventListener(
'WebViewJavascriptBridgeReady'
, function() {
callback(WebViewJavascriptBridge)
},
false
);
}
}
connectWebViewJavascriptBridge(function(bridge) {
bridge.init(function(message, responseCallback) {
console.log('Js got a message', message);
var data = {
'Javascript Responds': '测试中文!'
};
console.log('Js responding with', data);
responseCallback(data);
});
})
</script>
</html>
版权声明:
作者:Joe.Ye
链接:https://www.appblog.cn/index.php/2023/03/18/android-integrate-jsbridge/
来源:APP全栈技术分享
文章版权归作者所有,未经允许请勿转载。
THE END
0
二维码
打赏
海报
Android集成JsBridge
Github:https://github.com/lzyzsd/JsBridge
依赖
repositories {
maven { url "https://jitpack.io" }
}
dependencies {
api 'com……
文章目录
关闭
共有 0 条评论