User Interface Access from JavaScript on Android

For some reason, I have to use WebView in my Android application, and part of the business logic is in JavaScript (I run it using addJavascriptInterface ()). The problem is that I cannot change the user interface components of my application from the object associated with the script. This is explained in the documentation:

Note. The object attached to your JavaScript runs in a different thread, not in the thread in which it was built.

I am wondering if there is a workaround for the problem?

+5
source share
2 answers

Handler JavaScript runnables. , runnables .

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
    }
});

Activity runOnUIThread

mActivity.runOnUIThread(new Runnable() {
    @Override
    public void run() {
       // code here will run on UI thread
    }
});
+13

, , getActrivity().runOnUIThread(...) Javascript. , , WebViewCoreThread Javascript, , getActivity() null, NullPointerException. - , . , , JavaScript WeakReferences ui, , Javascript.

 myWebView.addJavascriptInterface(new Object() {
        private Handler handler = new Handler();
        private WeakReference<ProgressBar> progressBarRef = new WeakReference<ProgressBar>(
                myWebViewProgressBar);
        private WeakReference<WebView> myWebViewRef = new WeakReference<WebView>(
                myWebView);

        @SuppressWarnings("unused")
        public void onFirstImageLoad() {

            handler.post(new Runnable() {
                @Override
                public void run() {
                    ProgressBar progressBar = progressBarRef.get();
                    WebView webView = myWebViewRef.get();
                    if (progressBar != null) {
                        progressBar.setVisibility(View.GONE);
                    } 
                    if (webView != null) {
                        webView .setVisibility(View.VISIBLE);
                    }
                }
            });
        }
    }, "jsInterface");
+1

All Articles