简体   繁体   中英

Reloading a WebView with a JavaScript call from a loaded web page

I have a WebView in an app that loads a specific web page.

On that web page is a button that uses JavaScript to call a method within the Android activity to reload the URL in the WebView (effectively resetting the web app to its default state).

I've got all of the JavaScript interface to Android bit working thanks to a few threads here and I can pop up a Toast to show that the app is about to reload, but I'm getting an error with the WebView.loadUrl() call as follows.

java.lang.RuntimeException: java.lang.Throwable: A WebView method was called on thread 'JavaBridge'. All WebView methods must be called on the same thread. (Expected Looper Looper (main, tid 1) {1d015c84} called on Looper (JavaBridge, tid 122148) {33703881}, FYI main Looper is Looper (main, tid 1) {1d015c84})

I'm guessing that this is because the method that is doing the reload is not within the onCreate method for this activity which does all of the other WebView stuff but I'm not sure if this really is the problem and how to resolve it if it is - as the method that reloads the URL needs to be within the JavascripInterface class to be reachable from within the web-page.

Loading a page in a WebView componenet (or reloading) needs to be done on the UI thread for some reason, so simply wrapping the reload call in runOnUiThread resolves this issue.

    @JavascriptInterface
    public void reloadSite(){
        Toast.makeText(mContext, getString(R.string.reloadingWebApp), Toast.LENGTH_LONG).show();
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mWebView = (WebView) findViewById(R.id.activity_main_webview);
                mWebView.loadUrl(getString(R.string.web_app_url));
            }
        });
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM