Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access UI from JavaScript on Android

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?

like image 785
Mr.D Avatar asked Feb 25 '12 18:02

Mr.D


1 Answers

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
    }
});
like image 134
Olegas Avatar answered Oct 08 '22 00:10

Olegas