<Button
android:id="@+id/button"
android:layout_width="match_parent"
android:text="@string/button_name"
android:layout_height="dp"
/>
<!-- webview 演示web调用Java -->
<com.github.lzyzsd.jsbridge.BridgeWebView
android:id="@+id/webView"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</com.github.lzyzsd.jsbridge.BridgeWebView>
</LinearLayout>
3、java代码
//加载服务器网页
webView.loadUrl("https://www.baidu.com"); //必须和js同名函数。
webView.registerHandler("submitFromWeb", new BridgeHandler() {
@Override
public void handler(String data, CallBackFunction function) {
String str ="html返回给java的数据:" + data;
makeText(MainActivity.this, str, LENGTH_SHORT).show();
Log.i(TAG, "handler = submitFromWeb, data from web = " + data);
function.onCallBack( str + ",Java经过处理后:"+ str.substring(,));
}
});
//模拟用户获取本地位置
User user = new User();
Location location = new Location();
location.address = "xxx";
user.location = location;
user.name = "Bruce";
webView.callHandler("functionInJs", new Gson().toJson(user), new CallBackFunction() {
@Override
public void onCallBack(String data) {
makeText(MainActivity.this, "网页在获取你的信息", LENGTH_SHORT).show();
}
});
webView.send("hello");
webView.callHandler("functionInJs", "data from Java", new CallBackFunction() { @Override
public void onCallBack(String data) {
// TODO Auto-generated method stub
Log.i(TAG, "reponse data from js " + data);
}
});
js调用
var str1 = document.getElementById("text1").value;
var str2 = document.getElementById("text2").value; //调用本地java方法
window.WebViewJavascriptBridge.callHandler(
'submitFromWeb'
, {'param': str}
, function(responseData) {
document.getElementById("show").innerHTML = "send get responseData from java, data = " + responseData
}
);
//注册事件监听
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': 'Wee!'
};









