Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Webview loadUrl does not work when coming from a worker thread

I am developing an app that contains a web view. A certain times during the app it does a call to Webview loadUrl.

Sometimes the call will come directly from an event on the UI thread and other times it comes from an event on a background worker thread. When it originates from the background thread I do a call to runOnUIThead() to ensure the actual call to loadURL happens on the UI thread.

What I am experiencing is that loadUrl() works fine when originating from the UI thread, however it fails to work when it comes from a worker thread (even though the actual call to loadUrl happens via a runnable I pass into runOnUIThread()).

Having set a break point I can see that in both instances loadUrl() is being called on the UI thread. Yet it works in one case but not the other.

I am currently sifting through the Android Webview source code to see if I can track down why sometimes it works and sometimes it doesn’t. If anyone can shed any light on the matter it would be greatly appreciated.

--- UPDATE ---

I have tried a few suggestions from this post here: WebView loadUrl works only once

Mainly doing the following before calling loadUrl:

webView.clearCache(true);
webView.loadUrl("Url");

And:

webView.clearCache(true);
webView.clearView();
webView.reload();
webView.loadUrl("about:blank");
webView.loadUrl("Url");

Unfortunately neither of them work.

like image 242
Smalesy Avatar asked Nov 02 '22 07:11

Smalesy


1 Answers

In general, its not safe to create view outside of main thread.

In your particular case, this is not allowed, because WebView creates Handler() in its constructor for communication with UI thread. But since Handler's default constructor attaches itself to current thread, and current thread does not have Looper running, you're getting this exception.

You might think that creating a looper thread (that must be alive at least as long as WebView) might help you, but this actually a risky way to go. And I wouldn't recommend it.

You should stick with creating WebViews in main thread. All controls are usually optimized for fast construction, as they are almost always created in UI thread.

or You can call webview like this

runOnUiThread(new Runnable() {

            @Override
            public void run() {
                //    your webview method

            }
        });
like image 116
Hardik Chauhan Avatar answered Nov 11 '22 12:11

Hardik Chauhan