I'm building hybrid Android app with WebView that communicates with the device with JavaScriptInterface
annotation
From the WebView:
webView.addJavascriptInterface(someService, "someService");
The service implementation:
@JavascriptInterface
public void someMethod() {
//do some business logic..
}
Problem is that from the JavaScript I run it like this:
function callSomeMethod() {
someService.someMethod()
};
This call is synchronous, and would like something that will run asynchronously like:
function callSomeMethod(callback) {
someService.someMethod(function(result) {
if (result == 'success')
callback();
})
};
Preferably using promise:
function callSomeMethod() {
return someService.someMethod()
//someMethod returns promise
};
Does Android WebView has built in support for running JavaScript code asynchronously?
That solely depends on you. You just need to return immediately from the injected method, but be able to call JS code when the execution is complete. Something like this (note that it's only a rough sketch):
And in JavaScript you use it like this:
So the idea is that you pass the JS code you need to be called back as a string (because you can't pass a real JS object). This code will be called in the global context.
Locking in Java is needed because methods called from JS run on a dedicated thread, not on your app's UI thread.
Note that in M preview, an API for
postMessage
has been added to WebView, enabling to post asynchronous messages between Java and JS code.