使用异步任务在 webview 中加载 url 失败

load url in webview with asynch task fails

我正在尝试在另一个线程上加载我的 webview,以便在请求加载后我可以在屏幕上添加一个按钮。

我是这样做的:

private class CustomWebViewClient extends WebViewClient {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {

                MyView myView = new myView();
                myView.setUrl(url);
                myView.setWebView(view);

                new DownloadFilesTask().execute(myView);
            return true;
        }
    }


private class DownloadFilesTask extends AsyncTask<MyView, Integer, Long> {
        protected Long doInBackground(MyView... myView) {

            long totalSize = 0;
            MyView amyView = myView[0];

           WebView view = amyView.getWebView();
           String url = amyView.getUrl();
            view.loadUrl(url);

            return totalSize;
        }

        protected void onProgressUpdate(Integer... progress) {

        }

        protected void onPostExecute(Long result) {
            rl.setVisibility(View.VISIBLE);
        }
    }

我收到错误:

 Caused by: java.lang.RuntimeException: java.lang.Throwable: Warning: A WebView method was called on thread 'AsyncTask #2'. All

WebView methods must be called on the UI thread. Future versions of WebView may not support use on other threads.

如何在 url 加载后使视图可见?

您不应该在后台线程中加载 WebView;它需要在 UI 线程上加载。

我会为您的 WebView 添加一个侦听器,当 URL 完成加载后,您可以添加您的按钮。

yourWebView.setWebViewClient(new WebViewClient() {

   public void onPageFinished(WebView view, String url) {
        // add your button here
    } 
}); 

yourWebView.loadUrl(url);