WebViewClient onReceivedError已弃用,新版本不检测所有错误

在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无法加载?

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

此外,“错误代码109”(我猜这是net::ERR_ADDRESS_UNREACHABLE )不是一个HTTP错误代码,它是Chrome的错误代码。 onReceivedHttpError仅针对通过HTTP从服务器收到的错误进行调用。 当设备处于飞行模式时,它不可能从服务器接收到答复。

你也可以这样做:

 @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

快乐的编码!