关于android:WebViewClient onReceivedError已过时,新版本未检测到所有错误

WebViewClient onReceivedError deprecated, new version does not detect all errors

在Android SDK 23中,onReceivedError(WebView view, int errorCode, String description, String failingUrl)已被弃用,并替换为onReceivedError(WebView view, WebResourceRequest request, WebResourceError error)。但是,如果我将手机置于飞行模式并在WebView上加载URL,则只会调用该方法的不建议使用的版本。

onReceivedHttpError (WebView view, WebResourceRequest request, WebResourceResponse errorResponse)也不有用,因为它仅检测到高于500的错误,并且我得到的状态码为109。

是否有一种不建议使用的方法来检测我的WebView加载失败?


您还可以执行以下操作:

1
2
3
4
5
6
7
8
9
10
11
12
@SuppressWarnings("deprecation")
@Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
    // Handle the error
}

@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());
}

确保您导入android.annotation.TargetApi

祝您编程愉快!


请注意,您要测试的移动设备需要实际运行Android Marshmallow(API 23)。即使您使用API?? 23 SDK开发应用程序,然后在Android Lollipop上运行该应用程序,您仍然会得到"旧" onReceivedError,因为它是操作系统的功能,而不是SDK的功能。

此外,"错误代码109"(我想这是net::ERR_ADDRESS_UNREACHABLE)不是HTTP错误代码,而是Chrome的错误代码。仅针对通过HTTP从服务器收到的错误调用onReceivedHttpError。当设备处于飞行模式时,它可能无法收到来自服务器的回复。