Search code examples
androidwebviewwebviewclient

stop loading in webViewClient


In my WebView, I have multiple links in header. In Offline mode, I mustn't allow reload the page and keep that page as is and then, inform users about internet connection. I am able to catch links before it loads using shouldOverrideUrlLoading if I click other links. But if I click the same link, shouldOverrideUrlLoading is not being fired, instead, onLoadResource method is being called first. In that method I tried webView.stopLoading(); but it continues working and fire onReceivedError method and shows error report on the page.

Here is my 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);    
        }
    });

What I want is to be able to ensure that urls are not being fired if it is offline and inform about that.


Solution

  • Its a known issue and there is a bug reported for it. http://code.google.com/p/android/issues/detail?id=2887

    A number of workarounds have been suggested. e.g.

    1. Override onPageStarted
    2. Add JavascriptInterface by CommonsWare
    3. Disable WebView touch events

    Additionally, register a BroadcastReceiver to listen to network state changes and apply the workaround when the connectivity is lost. Network listener Android