Asynchronous JavaScript calls from Android WebView -


i'm building hybrid android app webview communicates device javascriptinterface annotation

from webview:

webview.addjavascriptinterface(someservice, "someservice"); 

the service implementation:

@javascriptinterface public void somemethod() {     //do business logic.. } 

problem javascript run this:

function callsomemethod() {     someservice.somemethod() }; 

this call synchronous, , 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 running javascript code asynchronously?

that solely depends on you. need return injected method, able call js code when execution complete. (note it's rough sketch):

private webview mwebview; private final object mlock = new object(); private string mjscallbackcode;  @javascriptinterface public void somemethod(string jscallbackcode) {     synchronized (mlock) {         mjscallbackcode = jscallbackcode;     }     // start business logic asynchronously, , return here immediately.     return; }  public void onbusinesslogiccompleted(bool success) {     string jscallbackcode;     synchronized (mlock) {         jscallbackcode = mjscallbackcode;     }     mwebview.loadurl("javascript:" + jscallbackcode + "(" + success + ");void(0);"); } 

and in javascript use this:

function callsomemethod(callback) {     window._somemethodcallback = callback;     someservice.somemethod(         '(function(success){' +         '    if (success) window._somemethodcallback();' +         '    delete window._somemethodcallback;' +         '})'     ); };     

so idea pass js code need called as string (because can't pass real js object). code called in global context.

locking in java needed because methods called js run on dedicated thread, not on app's ui thread.

note in m preview, api postmessage has been added webview, enabling post asynchronous messages between java , js code.


Comments

Popular posts from this blog

facebook - android ACTION_SEND to share with specific application only -

python - Creating a new virtualenv gives a permissions error -

javascript - cocos2d-js draw circle not instantly -