从已加载的网页重新加载带有JavaScript调用的WebView [英] Reloading a WebView with a JavaScript call from a loaded web page

查看:66
本文介绍了从已加载的网页重新加载带有JavaScript调用的WebView的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在加载特定网页的应用程序中有一个 WebView .

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

该网页上的一个按钮,使用JavaScript调用Android活动中的方法以将URL重新加载到WebView中(有效地将Web应用重置为默认状态).

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).

由于这里有一些线程,我已经可以连接到Android的所有JavaScript接口,并且可以弹出 Toast 来显示该应用程序即将重新加载,但是我出现如下所示的WebView.loadUrl()调用错误.

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

我猜这是因为执行此重载的方法不在该活动的 onCreate 方法之内,该方法执行所有其他 WebView 任务,但我不确定这是否真的是问题,以及如何解决(因为要重新加载URL的方法需要在JavascripInterface类中才能从网页内访问).

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.

推荐答案

出于某种原因,需要在UI线程上将页面加载到 WebView componenet中(或重新加载) runOnUiThread 中的重载调用解决了此问题.

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

这篇关于从已加载的网页重新加载带有JavaScript调用的WebView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆