简体   繁体   English

如何使用 Android Webview 检查链接是否脱机或损坏?

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

I use an Android Webview to load a URL like this:我使用 Android Webview 加载这样的 URL:

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?如何检测 webView 应加载的链接是否脱机或损坏?

Yes you can do detect broken links in WebView using onRecicedError() in WebViewClient Class.是的,您可以使用 WebViewClient 类中的onRecicedError()检测 WebView 中的断开链接。

You have to create an object for WebViewClient and implement onRecicedError() method and set WebViewClient Object using setWebViewClient() method in WebView你必须创建WebViewClient对象和实施onRecicedError()方法和一套WebViewClient对象使用setWebViewClient()方法中的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());
  }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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