As I work on developing an Android app using HTML5/JavaScript, I've encountered some limitations. One challenge I face is calling a function implemented in Java code from within JavaScript, specifically to create a particular type of dialog. While the process seems straightforward, there are nuances involved:
public class MyClass () {
// other stuff
public void createMyDialog (/* arguments */) {
DialogBuilder builder = ...
builder.setItems(myItems, new DialogInterface.OnClickListener () {
@Override
public void OnClick (DialogInterface dialog, int which) {
droidGap.loadUrl(/* what now? */);
}
});
}
}
To expose this class to JavaScript, the following steps can be followed:
MyClass myClass = new MyClass();
appView.addJavascriptInterface(myClass, "myClass");
Although this setup allows for access to window.myClass.createMyDialog()
from JavaScript, I desire to include a callback function that would receive the which
variable as an argument. This requires modifying the method signature to:
public void createMyDialog (final String callback)
and invoking it with something like
window.myClass.createMyDialog(
function (which) {
alert(which);
}
);
I have managed to make this work by passing the function as a string and then executing
appView.loadUrl("javascript:(" + callback + ")(" + which + ");");
in Java. However, this approach feels less than ideal and has a notable drawback – which brings me to my main concern. When calling createMyDialog
from JavaScript within a class context, such as:
function myJSClass () {
this.myVar = -1;
this.myFunc = function () {
window.myClass.createMyDialog(
function (which) {
this.myVar = which;
}
);
}
}
var myObj = new myJSClass();
myObj.myFunc();
The issue arises when trying to reference this
, which ends up pointing to window
instead of the intended class instance due to the call originating from Java. Various solutions like storing var _this = this
or utilizing bind
have not proven effective in preserving the correct context.
I am aware that frameworks like PhoneGap offer functionalities similar to what I'm attempting with navigator.notification.confirm
. So, what would be the recommended approach in this scenario?
Your insights are greatly appreciated!