如何从AsyncTask更新webview

时间:2013-02-26 17:06:17

标签: android webview android-asynctask

我有一个应用程序从网络获取xml文件,将其解析为检索我必须缓存的网站网页的路径.eg

/services/orthopaedics.php

。 我可以成功下载需要缓存的所有页面的路径。目前我在AsyncTask中执行此操作。 webservice调用的结果(页面路径)存储在AsyncTask的doInBackground方法的contentsValues中。然后我在onPostExecute()方法中迭代这个内容值,在那里我可以逐个加载webview的loadUrl()方法中的网页。此webview不可见,因为它仅用于缓存目的。

问题在于,当不可见的webview正在加载用户可以看到的另一个webview并且要显示该站点的索引页面时,它的加载速度会变慢。出现白色屏幕,直到看不见的webview停止加载缓存。在一个phoe上需要大约4秒才可以接受,但在Android平板电脑上大约需要30秒。

我知道对webview的调用必须在UI线程上,这就是我在onPostExecute方法中加载网页(不可见的webview)的原因。是否有可能以某种方式将页面加载到doInBacground方法的缓存中,但将webview.loadUrl()放在runOnUiThread(new Runnable)中?

我将简要介绍下面的含义。

private class AsyncCacheSite extends AsyncTask<String, ContentValues, ContentValues>{

        ProgressDialog progressDialog;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            Log.e(TAG, "about to load main page");
            webView.loadUrl(mobileWebsiteUrl, getHeaders());

            progressDialog = new ProgressDialog(MainActivity.this);
            progressDialog.setTitle("Connecting to Server");
            progressDialog.setMessage("Caching website for offline use...");
            progressDialog.setIndeterminate(true);
            progressDialog.show();
        }

        @Override
        protected ContentValues doInBackground(String... params) {
            ContentValues cv = null;

            try {
                //call the service to get the xml file containing paths
                cv = ws.checkForUpdates();


            } catch (Exception e) {
               e.printStackTrace();
            }

//iterate through the xml file geting the paths
.......
.......
.......
runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                // TODO Auto-generated method stub
loadUrlIntoCache(page);

                            }
                        })


            return null; 

        }



        @Override
        protected void onPostExecute(ContentValues result) {
            super.onPostExecute(result);



            progressDialog.dismiss();


    }//end of postExecute

 }//end of asyncTask



public void loadUrlIntoCache(String pageUrl){

        WebView wv2 = new WebView(MainActivity.this);

        wv2.getSettings().setSupportZoom(true);
        wv2.getSettings().setBuiltInZoomControls(true);
        wv2.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
        wv2.setScrollbarFadingEnabled(true);
        wv2.getSettings().setLoadsImagesAutomatically(true);
        wv2.getSettings().setDomStorageEnabled(true);
        wv2.getSettings().setAppCacheEnabled(true);
        // Set cache size to 8 mb by default. should be more than enough
        wv2.getSettings().setAppCacheMaxSize(1024*1024*32);
        // This next one is crazy. It's the DEFAULT location for your app's cache
        // But it didn't work for me without this line.
        // UPDATE: no hardcoded path. Thanks to Kevin Hawkins
        String appCachePath = getApplicationContext().getCacheDir().getAbsolutePath();

        wv2.getSettings().setAppCachePath(appCachePath);
        wv2.getSettings().setAllowFileAccess(true);
        wv2.getSettings().setJavaScriptEnabled(true);
       // wv2.setWebViewClient(new WebViewClient());

////////////////////////////////////////////////////////////////////////////////////////
/////the webviewclient below is the code you gave me to overcome the redirecting issue//
////////////////////////////////////////////////////////////////////////////////////////
webView.setWebViewClient(new WebViewClient() {
public boolean shouldOverrideUrlLoading(WebView view, String url){
// do your handling codes here, which url is the requested url
// probably you need to open that url rather than redirect:
view.loadUrl(url);
return false; // then it is not handled by default action
}
});

        wv2.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
        wv2.setVisibility(View.GONE); 

        wv2.loadUrl(mobileWebsiteUrl + pageUrl, getHeaders());
        Log.e(TAG, "loading " + mobileWebsiteUrl + pageUrl);



    }

3 个答案:

答案 0 :(得分:3)

我认为唯一的解决方案是在doInBackground中使用http请求加载数据然后使用 publishProgress中的loadData

答案 1 :(得分:2)

可悲的是,你无法加载&#34;来自AsyncTask的URL。所有&#34; WebView&#34;必须从主线程调用方法。

您所能做的就是在第二个线程中更新进度对话框。请检查此答案Webview with asynctask on Android

答案 2 :(得分:0)

需要从UI线程调用WebView。如果您碰巧可以访问主循环程序,则可以通过UI线程处理程序创建,设置和加载页面。

    //Code for creating an instance of Webview inside AsyncTask
    WebView wv = null;
    final Object lock = new Object();
    final int TIMEOUT_MS = 3000;
    AtomicReference<WebView> holder = new AtomicReference<>(); //use to pass the created webview back to worker thread.
    Handler mainHandler = new Handler(Looper.getMainLooper());
    try {
        synchronized (lock) {
            while (wv == null) {
                mainHandler.post(() -> {
                    synchronized (lock) {
                        WebView localWebView = new WebView(context);
                        setWebViewCache(context, localWebView); //configure the cache to your desired location.
                        holder.set(localWebView); //use this line to pass out the created instance from the UI thread back to your async task.
                        lock.notify();
                    }
                });
                lock.wait(TIMEOUT_MS);
                wv = holder.get();
            }
        }
    } catch (InterruptedException ie) {
        Log.e(TAG, "creating prefetch webview times out");
    }

接下来,您要在AsyncTask中使用所需的URL加载Webview。

  synchronized (lock) {
            mainHandler.post(() -> {
                wv.setWebViewClient(new WebViewClient() {
                    @Override
                    public void onPageFinished(WebView view, String url) {
                        super.onPageFinished(view, url);
                        //override with behavior you want after load finishes, make sure to notify the workerthread to proceed.
                        synchronized (lock) {
                            lock.notify();
                        }
                    }
                });
                wv.loadData(html, mimeType, encoding); //here load the url you want
            });
            lock.wait(TIMEOUT_MS);
        }

希望我的代码可以提供帮助。