在webViewClient中停止加载

时间:2013-03-19 06:22:59

标签: android webview webviewclient

在我的WebView中,我在标题中有多个链接。在离线模式下,我不能允许重新加载页面并按原样保留该页面,然后通知用户有关互联网连接的信息。如果我点击其他链接,我可以在使用shouldOverrideUrlLoading加载之前捕获链接。但是,如果我点击相同的链接,shouldOverrideUrlLoading没有被触发,而是首先调用onLoadResource方法。在该方法中,我尝试webView.stopLoading();,但它继续工作并触发onReceivedError方法,并在页面上显示错误报告。

这是我的WebClient:

webView.setWebViewClient(new WebViewClient() {

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if(MyApplication.getInstance().isOnline()) {
                return false;
            }

            Toast.makeText(getApplicationContext(), "Please check Internet connection and try again.", Toast.LENGTH_SHORT).show();
            return true;
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            Log.i("ON_PAGE_START", "RUNNING ============>" + url);
            if (MyApplication.getInstance().isOnline()) {
                super.onPageStarted(view, url, favicon);
            } else {
                webView.stopLoading();
            }
        }

        @Override
        public void onLoadResource(WebView view, String url) { 

            if (MyApplication.getInstance().isOnline()) {
                super.onLoadResource(view, url);
            } else {
                webView.stopLoading();                  
            }
        }

        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {               

            view.stopLoading();

            Toast.makeText(getApplicationContext(), "Please check Internet connection and try again.", Toast.LENGTH_SHORT).show();
            super.onReceivedError(view, errorCode, description, failingUrl);    
        }
    });

我想要的是能够确保在离线时不会触发网址并告知相关信息。

3 个答案:

答案 0 :(得分:4)

它是一个已知问题,并且报告了一个错误。 http://code.google.com/p/android/issues/detail?id=2887

已经提出了许多解决方法。 e.g。

  1. Override onPageStarted
  2. CommonsWare
  3. Add JavascriptInterface
  4. Disable WebView touch events
  5. 此外,注册BroadcastReceiver以侦听网络状态更改并在连接丢失时应用解决方法。 Network listener Android

答案 1 :(得分:1)

我知道它的帖子很老但是感谢这篇文章,这有助于我解决问题!!!

我有类似的问题,stopLoading解决了我的问题:)

ifOverrideUrlLoading如果进入新页面或者如果有重定向但是没有像点击iframe等那样被调用。我想在我的应用程序中实现类似的行为,我意识到onPageStarted被调用但是没有shouldOverrideUrlLoading。

我没有覆盖onLoadResource,只是onPageStarted,因为onLoadResource在onPageStarted之后被调用。 OnPageStarted检查是否脱机,在这种情况下不加载。希望这有助于某人。

答案 2 :(得分:1)

我认为在onLoadRessource(..)和onPageStarted()中它应该是

view.stopLoading();

在你的其他地方{..}

相关问题