Java 如果加载时间超过特定时间,则 Android 超时 webview

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22759978/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 17:44:57  来源:igfitidea点击:

Android Timeout webview if it takes longer than a certain time to load

javaandroidwebviewandroid-progressbar

提问by Paddy1990

I Want to timeout my webview if it takes a long time to load showing an error message. I'm using setWebViewClientbecause I need to use the public void onReceivedSslError (WebView view, SslErrorHandler handler, SslError error).

如果加载显示错误消息需要很长时间,我想使我的 webview 超时。我正在使用,setWebViewClient因为我需要使用public void onReceivedSslError (WebView view, SslErrorHandler handler, SslError error).

I've been looking around and saw I can use the method onProgressChanged(WebView view, int newProgress). Now I can't use this method in setWebViewClientand can't figure out how to go about solving this problem. Another issue I have is that the progress bar never goes away once the page is loaded, I can't add a breakpoint to the method public void onPageFinished(WebView view, String url)either.

我一直环顾四周,看到我可以使用该方法onProgressChanged(WebView view, int newProgress)。现在我无法使用这种方法setWebViewClient,也无法弄清楚如何解决这个问题。我遇到的另一个问题是,加载页面后进度条永远不会消失,我也无法向该方法添加断点public void onPageFinished(WebView view, String url)

Web View Settings Method:

网页视图设置方法:

public void WebViewSettings(){

    webView = (WebView) findViewById(R.id.webview);
    webView.getSettings().setJavaScriptEnabled(true);
    webView.getSettings().setBuiltInZoomControls(true);
    webView.getSettings().setSupportZoom(true);
    webView.getSettings().setLoadWithOverviewMode(true);
    webView.canGoBack();

    webView.setWebViewClient(new WebViewClient(){

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if (Uri.parse(url).getHost().equals(urlString)) {
                // This is my web site, so do not override; let my WebView load the page
                return false;
            }
            // Otherwise, the link is not for a page on my site, so launch another Activity that handles URLs
            Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
            startActivity(intent);
            return true;
        }

        @Override
        public void onLoadResource(WebView view, String url) {
            // Check to see if there is a progress dialog
            if (progressDialog == null) {
                progressDialog = new ProgressDialog(context);
                progressDialog.setTitle("Loading...");
                progressDialog.setMessage("Please wait.");
                //progressDialog.setCancelable(false);
                progressDialog.setIndeterminate(true);
                progressDialog.show();
            }
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            // Page is done loading;
            // hide the progress dialog and show the webview
            if (progressDialog.isShowing()) {
                progressDialog.dismiss();
                progressDialog = null;
                webView.setEnabled(true);
            }
        }

        @Override
        public void onReceivedSslError (WebView view, SslErrorHandler handler, SslError error) {
             handler.proceed();
        }

        @Override
        public void onReceivedError(WebView view, int errorCod,String description, String failingUrl) {
            Toast.makeText(context, "Your Internet Connection May not be active Or " + description , Toast.LENGTH_LONG).show();
        }
    });
}

So the issues I have are the progress bar doesn't get removed once the web page has loaded and I need to timeout the webview if it take over a certain amount of time to load. It looks like the progress bar is shown, then is disappears like it should, then starts loading again and wont stop. Thanks

所以我遇到的问题是,一旦网页加载完毕,进度条就不会被删除,如果 webview 加载时间超过了一定的时间,我需要超时。看起来进度条显示出来,然后像它应该的那样消失,然后再次开始加载并且不会停止。谢谢

采纳答案by Solution

I have updated your webview setting method please find below updated code. I have added one loaderTimerTask class. Added code for timer and put comment for more understanding. Please update this code if you need.

我已经更新了你的 webview 设置方法,请在下面找到更新的代码。我添加了一个 loaderTimerTask 类。添加了计时器的代码并添加注释以获取更多理解。如果需要,请更新此代码。

private boolean isPageLoadedComplete = false; //declare at class level

public void WebViewSettings(){

webView = (WebView) findViewById(R.id.webview);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setBuiltInZoomControls(true);
webView.getSettings().setSupportZoom(true);
webView.getSettings().setLoadWithOverviewMode(true);
webView.canGoBack();

 /**
  *I had put code here
  */
Timer myTimer = new Timer();
    //Start this timer when you create you task
myTimer.schedule(loaderTask, 3000); // 3000 is delay in millies

webView.setWebViewClient(new WebViewClient(){

    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        if (Uri.parse(url).getHost().equals(urlString)) {
            // This is my web site, so do not override; let my WebView load the page
            return false;
        }
        // Otherwise, the link is not for a page on my site, so launch another Activity that handles URLs
        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
        startActivity(intent);
        return true;
    }

    @Override
    public void onLoadResource(WebView view, String url) {
        // Check to see if there is a progress dialog
        if (progressDialog == null) {
            progressDialog = new ProgressDialog(context);
            progressDialog.setTitle("Loading...");
            progressDialog.setMessage("Please wait.");
            //progressDialog.setCancelable(false);
            progressDialog.setIndeterminate(true);
            progressDialog.show();
        }
    }

    @Override
    public void onPageFinished(WebView view, String url) {
            isPageLoadedComplete = true;
        // Page is done loading;
        // hide the progress dialog and show the webview
        if (progressDialog.isShowing()) {
            progressDialog.dismiss();
            progressDialog = null;
            webView.setEnabled(true);
        }
    }

    @Override
    public void onReceivedSslError (WebView view, SslErrorHandler handler, SslError error) {
         handler.proceed();
    }

    @Override
    public void onReceivedError(WebView view, int errorCod,String description, String failingUrl) {
        Toast.makeText(context, "Your Internet Connection May not be active Or " + description , Toast.LENGTH_LONG).show();
    }
});
}

 /**
  *This class is invoke when you times up.
  */
 class loaderTask extends TimerTask {
  public void run() {
    System.out.println("Times Up");
    if(isPageLoadedComplete){
    }else{
        if (progressDialog.isShowing()) {
            progressDialog.dismiss();
            progressDialog = null;
            webView.setEnabled(true);
        }
        //show error message as per you need.
    }
  }
}