Set loadURLTImeOutValue on WebView

前端 未结 6 1117
我在风中等你
我在风中等你 2020-11-29 06:32

I\'m working with PhoneGap and Android and have my .html and js files on an external server. When I use the following code, the app loads my external .html files and everyt

6条回答
  •  迷失自我
    2020-11-29 07:20

    The use of Thread class bothers me calling the WebView from the run function will lead to an exception as the WebView is created and used in another thread. I would perform this with an AsyncTask. In this example, I use an AsyncTask to load an error file into the WebView if the timeout was reached. If the page loads properly I cancel the AsyncTask. The onPostExecute runs in the UI thread so there is no thread safety problem to interact with the WebView:

    private class CustomWebViewClient extends WebViewClient {
        boolean mPageLoaded;
        final int mTimeoutLength = 20000;
        WebView mView;
        TimeoutCheck timeoutCheckTask;
    
        public CustomWebViewClient()
        {
            super();
            mPageLoaded = false;
        }
    
        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            mView = view;
    
            timeoutCheckTask  = new TimeoutCheck();
            timeoutCheckTask.execute(null,null);
        }
    
        public void onPageFinished(WebView view, String url) {
            mPageLoaded = true;
            timeoutCheckTask.cancel(true);
        }
    
        private class TimeoutCheck extends AsyncTask {
            protected Void doInBackground(Void... params) {
                long count = 0;
                while (count < mTimeoutLength)
                {
                    try
                    {
                        Thread.sleep( 1000 );
                    }
                    catch ( InterruptedException e )
                    {
                        e.printStackTrace();
                    }
    
                    // Escape early if cancel() is called
                    if (isCancelled()) break;
                    count += 1000;
                }
                return null;
            }
    
            protected void onPostExecute(Void result) {
                if(!mPageLoaded) {
                    mbLoadedErrFile = true;
                    //load error file into the webview
                    mView.loadUrl("file:///android_asset/url_err_timeout.html");
                }
            }
        }
    

提交回复
热议问题