when i need to do something like this i use a substrate layer like this:
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];
};
}());
so now when you have the Java code like (assuming you exposed the same object as "Native"):
java
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)");
}
}
and use it like this:
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();
the substrate layer is now reusable and standard so you don't have to worry about setting global variables or anything crazy like that, plus it works with any number of arguments both in and out of the native layer...
hope this helps -ck