简体   繁体   中英

How to check if Link is offline or broken with Android Webview?

I use an Android Webview to load a URL like this:

mWebView = (WebView)v.findViewById(R.id.webView);
mWebView.getSettings().setLoadWithOverviewMode(true);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.getSettings().setUseWideViewPort(true);
mWebView.getSettings().setBuiltInZoomControls(true);
mWebView.getSettings().setDomStorageEnabled(true);

mWebView.loadUrl("someUrl");

How can I detect if the link the webView should load is offline or broken?

Yes you can do detect broken links in WebView using onRecicedError() in WebViewClient Class.

You have to create an object for WebViewClient and implement onRecicedError() method and set WebViewClient Object using setWebViewClient() method in WebView

Eg:

webView.setWebViewClient(new WebViewClient() {
  @SuppressWarnings("deprecation")
  @Override
  public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
      if(errorCode == 404){
             Log.d("Webview", "Invalid URL: "+url);
      }
      else if(errorCode == 500){
           Log.d("Webview", "Internal Server error: "+url);
      }
  }

  @TargetApi(android.os.Build.VERSION_CODES.M)
  @Override
  public void onReceivedError(WebView view, WebResourceRequest req, WebResourceError rerr) {
    // Redirect to deprecated method, so you can use it in all SDK versions
    onReceivedError(view, rerr.getErrorCode(), rerr.getDescription().toString(), req.getUrl().toString());
  }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM