若感觉排版不舒服,可移步【Android中实现Native与H5的通信方案汇总】
一、利用JsBridge实现Native与H5的双向通信
Android中的JSBridge是H5与Native通信的桥梁,其作用是实现H5与Native间的双向通信。在Android中展现H5也就用到了Webview,之前写了一篇文章Android WebView简单使用以及实现native与h5交互,主要就是介绍一个webview的用法介绍及WebViewClient
和WebChromeClient
一些常用的方法。在结尾的时候简单介绍了下Native与H5的相互调用,也没怎么讲具体怎么用,今天就在这里做一下笔记。
既然这里讲述了JsBridge,所以可以移步这里看看lzyzsd/JsBridge,里面有介绍使用方法。我这下面也接着啰嗦一下:
1、引入资源文件
repositories {
// ...
maven { url "https://jitpack.io" }
}
dependencies {
compile 'com.github.lzyzsd:jsbridge:1.0.4'
}
2、布局文件
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<com.github.lzyzsd.jsbridge.BridgeWebView
android:id="@+id/JsBridgeWebView"
android:layout_width="match_parent"
android:layout_height="match_parent">
</com.github.lzyzsd.jsbridge.BridgeWebView>
<Button
android:id="@+id/android_call_js"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Android调用js"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
</RelativeLayout>
3、在项目assets目录下存放的以下文件
+ jsbridge.js文件
function connectWebViewJavascriptBridge(callback) {
if (window.WebViewJavascriptBridge) {
callback(WebViewJavascriptBridge)
} else {
document.addEventListener('WebViewJavascriptBridgeReady', function () {
callback(WebViewJavascriptBridge)
}, false)
}
}
connectWebViewJavascriptBridge(function (bridge) {
bridge.init(function (message, responseCallback) {