I might be a few years too late, but here is how I had to solve it since none of these answers worked.
I ended up using onReceivedTitle and comparing the title with the title of the page (in this case "page not found") from the site I was trying to open.
webview.setWebChromeClient(new WebChromeClient() {
@Override
public void onReceivedTitle(WebView view, String title) {
// TODO Auto-generated method stub
super.onReceivedTitle(view, title);
CharSequence pnotfound = "The page cannot be found";
if (title.contains(pnotfound)) {
pagenotfound = true;
view.stopLoading();
webview.loadUrl("https://www.google.com/search?hl=en&q=stackoverflow");
}
}
public void onProgressChanged(WebView view, int progress) {
activity.setProgress(progress * 1000);
}
});
webview.setWebViewClient(new WebViewClient() {
@Override
public void onReceivedError(WebView view, int errorCode,
String description, String failingUrl) {
Toast.makeText(activity, "Oh no! " + description,
Toast.LENGTH_SHORT).show();
}
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
public void onPageFinished(WebView view, String url) {
if (dialog.isShowing()) {
dialog.dismiss();
}
}
});
The "pnotfound" will be different from site to site. But usually one site use the same "page not found" therefore you can use the Title on the site.
You might want to add a else if for if you're using multiple sites.
Hope it helps for someone.
该博客介绍了如何在Android的WebView中处理页面加载错误。通过监听`onReceivedTitle`事件,当页面标题包含特定的“页面未找到”文本时,停止加载当前页面,并重定向到Google搜索。同时,它还展示了如何使用`onProgressChanged`更新进度条,并在`onPageFinished`中关闭加载对话框。在遇到错误时,会显示一个Toast提示。
4094

被折叠的 条评论
为什么被折叠?



