在我的应用中,我从网络服务接收URL作为字符串并将其加载到WebView。
mainContentText = (WebView) findViewById(R.id.mainContentText);
mainContentText.getSettings().setJavaScriptEnabled(true);
mainContentText.setWebViewClient(new CustomWebClient());
mainContentText.loadUrl(url);
private class CustomWebClient extends WebViewClient{
private static final String TAG = "WebWiewActivity";
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
Log.d(TAG, "loading: " + url);
return false;
}
@Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
super.onReceivedError(view, errorCode, description, failingUrl);
Log.e(TAG, String.format("*ERROR* Code: %d Desc: %s URL: %s", errorCode, description, failingUrl));
}
}
当测试网址不好的情况(随机字符串,url = "abc"
)时,我只会收到一个默认错误页面,但onReceivedError
没有shouldOverrideUrlLoading
回调,而且没有例外
我怎么能抓住这种情况呢?
答案 0 :(得分:2)
我遇到了同样的问题,我解决了它,如下所示:
private class CustomWebClient extends WebViewClient {
private static final String TAG = "WebWiewActivity";
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
Log.d(TAG, "loading: " + url);
return false;
}
@Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
super.onReceivedError(view, errorCode, description, failingUrl);
*************************************
// do error handling
*************************************
}
@Override
public void onPageFinished(String url) {
// url validation
if (!Patterns.WEB_URL.matcher(url).matches()) {
*************************************
// do error handling
*************************************
}
}
}
我在 onPageFinished(String url)方法中添加了一些逻辑来检查url是否有效,并且当URL不好时你可以捕获异常(随机字符串,url =“abc “)。
答案 1 :(得分:0)
如果WebView无法处理url,则似乎在onPageStarted回调中返回“ about:blank”。不知道这比小邹的答案好还是坏。
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
if (url.equals("about:blank"))
// handle no connection
}