WebViewClient onReceivedError的IF()判断不生效问题咨询
Hey there! Let's break down why your onReceivedError if-condition isn't firing as expected, and fix that Toast behavior too. These are super common pitfalls with Android WebViews, so let's tackle them step by step:
1. You might be using the wrong onReceivedError overload
Android changed how error handling works starting with API 23 (Marshmallow). The old onReceivedError(WebView view, int errorCode, String description, String failingUrl) method doesn't get triggered for main resource loading errors on API 23+.
To cover all Android versions:
- For API 23+: Override the newer overload with
WebResourceRequest:@Override public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) { super.onReceivedError(view, request, error); int errorCode = error.getErrorCode(); // Your if-check here if (errorCode == WebViewClient.ERROR_HOST_LOOKUP) { Toast.makeText(view.getContext(), "Failed to find host", Toast.LENGTH_SHORT).show(); } } - For backward compatibility: Keep the old overload too, so devices running older Android versions can catch errors:
@Override public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) { super.onReceivedError(view, errorCode, description, failingUrl); if (errorCode == WebViewClient.ERROR_HOST_LOOKUP) { Toast.makeText(view.getContext(), "Failed to find host", Toast.LENGTH_SHORT).show(); } }
2. Your if-condition might be checking the wrong error code
It's easy to target the wrong error code without realizing it. First, log the actual error details to see what's happening:
// In either onReceivedError overload Log.d("WebViewDebug", "Error Code: " + errorCode + ", Description: " + description);
Check the logcat output to see which error code is actually being thrown. Common codes include:
WebViewClient.ERROR_HOST_LOOKUP: Failed to resolve the hostnameWebViewClient.ERROR_CONNECT: Couldn't connect to the serverWebViewClient.ERROR_TIMEOUT: Connection timed out
Adjust your if-condition to match the actual code you're seeing.
3. Toast not showing? Check context and thread
If your if-check is working but Toast isn't popping up:
- Use the right context: Always use
view.getContext()instead of an Activity context that might be destroyed. - Ensure you're on the main thread: While
onReceivedErrorruns on the main thread by default, if you've added any async logic, wrap the Toast call in apost():view.post(() -> { Toast.makeText(view.getContext(), "Load failed!", Toast.LENGTH_SHORT).show(); });
4. Double-check you set the WebViewClient
This sounds obvious, but it's easy to forget! Make sure you've attached your custom WebViewClient to your WebView instance:
WebView webView = findViewById(R.id.your_webview); webView.setWebViewClient(new CustomWebViewClient());
Without this, the default WebViewClient will be used, and your overridden methods won't run.
内容的提问来源于stack exchange,提问作者roberto cancello

