For some reasons I have to use WebView in my Android application and part of business logic is contained in JavaScript (I run it using addJavascriptInterface()). The problem is that I can't modify the UI components of my application from object bound to the script. That's explained in the documentation:
Note: The object that is bound to your JavaScript runs in another thread and not in the thread in which it was constructed.
I'm wondering if there is some workaround for this problem?
You need to pass Handler instance to your JavaScript interface and use it to post runnables there. If this handler will be created on UI thread, runnables posted there will also be invoked on the UI thread.
Handler mHandler = new Handler(); // must be created on UI thread, e.g. in Activity onCreate
// from javascript interface...
mHandler.post(new Runnable() {
@Override
public void run() {
// code here will run on UI thread
}
});
Another workaround is to use Activity
's method runOnUIThread
mActivity.runOnUIThread(new Runnable() {
@Override
public void run() {
// code here will run on UI thread
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With