当我需要做这样的事情时,我会使用这样的基板层:
javascript
(function() {
var callbacks = {};
function getNewId() {
return Math.round(Math.random() * 999999999);
}
window.__withCallback = function(func, context, callback, params) {
var cbId = getNewId(),
args = Array.prototype.slice.call(arguments, 2);
while (cbId in callbacks) {
cbId = getNewId();
}
args.unshift(cbId);
callbacks[cbId] = { context: context, callback: callback };
func.apply(Native, args);
};
window.__callbackFromNative = function(id, params) {
var args,
cbItem = callbacks[id];
if (cbItem && typeof(cbItem.callback) === 'function') {
args = Array.prototype.slice.call(arguments, 1);
cbItem.callback.apply(cbItem.context, args);
}
delete callbacks[id];
};
}());
所以现在当你有 Java 代码时(假设你暴露了与“Native”相同的对象):
爪哇
class Native {
public void test (long callbackId, String param1, String param2) {
// do java stuff in here
// webView is your webView
webView.loadUrl("javascript:__callbackFromNative(" + callbackId + ", 'yay', 69)");
}
}
并像这样使用它:
javascript
var awesome = {
test2: function(arg1, arg2) {
// callback
},
startTest: function() {
// here's the way you pass "this" to "Native.test",
// this.test2 is the function you want to "callback" to
// the rest are all params
__withCallback(Native.test, this, this.test2, "xxx", 'yay');
}
};
awesome.startTest();
底层现在是可重用和标准的,所以你不必担心设置全局变量或任何类似的疯狂,而且它可以在本地层内外使用任意数量的参数......
希望这会有所帮助-ck