一 : TS篇
A :JS调用JAVA
/**
* 点击按钮
* Click the button
*/
private onButtonClick(e: egret.TouchEvent) {
// this.textfield.text = "点击了按钮";
console.log(`game button 点击了 , 开始调用JAVA函数`);
let $obj : Object = {
"name" : "Aonaufly",
"occupation" : "warrior"
};
window["WebViewJavascriptBridge"].callHandler(
'JS2JAVA'
, JSON.stringify($obj)
, function(responseData) {
// this.textfield.text = `enterGame 2 Android callback param : ${responseData}`;
console.log(`enterGame 2 Android callback param : ${responseData}`);
}
);
}
PS 参数
①,JAVA的方法(string类型), 此处我定义的是“JS2JAVA”
②,JS给JAVA传递的参数
③,回调函数,供JAVA调用,回调函数的参数responseData,由JAVA回调给JS使用
B : JS注册方法供JAVA调用
private connectWebViewJavascriptBridge( callback : Function ) : void {
if (window["WebViewJavascriptBridge"]) {
callback(window["WebViewJavascriptBridge"])
} else {
document.addEventListener(
'WebViewJavascriptBridgeReady'
, function() {
callback(window["WebViewJavascriptBridge"])
},
false
);
}
}
protected createGameScene(): void {
this.connectWebViewJavascriptBridge(function (bridge) {
bridge.init(function(message, responseCallback) {
console.log('JS got a message', message);
var data = {
'Javascript Responds': '测试中文!'
};
if (responseCallback) {
console.log('JS responding with', data);
responseCallback(data);
}
});
/// Java 调 JS
bridge.registerHandler("JAVA2JS", function(data, responseCallback) {
if (responseCallback) {
var responseData = "Javascript Says Right back aka!";
// this.textfield1.text = JSON.stringify(data);
console.log(JSON.stringify(data));
responseCallback(responseData);
}
});
})
}
注意 :
“JAVA2JS” , 既是在TS端注册了一个“JAVA2JS”的方法,供JAVA端来调用,
二 : JAVA篇
①,需要下载jsBridge类库 : https://github.com/lzyzsd/JsBridge
②,需要获得前端游戏的html地址 : http://www.xxx.com/index(比如)
重点:需要使用WebView控件
A : TS调用JAVA
webView.registerHandler("JS2JAVA", new BridgeHandler() {
@Override
public void handler(String data, CallBackFunction function) {
// Log.i(TAG, "handler = submitFromWeb, data from web = " + data);
makeText(MainActivity.this, "handler = submitFromWeb, data from web = " + data, LENGTH_SHORT).show();
function.onCallBack("submitFromWeb exe, response data 中文 from Java");
}
});
注意 , TS端和JAVA的方法名称字符串一定要一致,此处用的是“JS2JAVA”
B:JAVA调用TS
@Override
public void onClick(View v) {
if (button.equals(v)) {
makeText(MainActivity.this, "JAVA调用JS ", LENGTH_SHORT).show();
webView.callHandler("JAVA2JS", "data from Java", new CallBackFunction() {
@Override
public void onCallBack(String data) {//functionInJs
// TODO Auto-generated method stub
Log.i(TAG, "reponse data from js " + data);
makeText(MainActivity.this, "reponse data from js ", LENGTH_SHORT).show();
}
});
}
}
同样的“JAVA2JS”方法名称要一致。
附送IOS类库地址 : https://github.com/wangjiaojiao77/WebViewJavascriptBridge