当WebView加载url时,用户可能无法访问互联网(例如,他使用路由器,但帐户中的钱被终止)。
在这种情况下,WebView显示自己的html"网页不可用"。
我尝试使用自定义WebViewClient和回调:
@Override
public void onReceivedError(android.webkit.WebView view, WebResourceRequest request, WebResourceError error) {
super.onReceivedError(view, request, error);
}
但它没有被调用。
在WebView中加载url时如何处理脱机?
附言:请不要提供检查网络状态的解决方案。我只对WebView感兴趣。
试试这个:
@Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
Log.e(String.valueOf(errorCode), description);
// API level 5: WebViewClient.ERROR_HOST_LOOKUP
if (errorCode == -2) {
String summary = "<html><body style='background: black;'><p style='color: red;'>Unable to load information. Please check if your network connection is working properly or try again later.</p></body></html>"; view.loadData(summary, "text/html", null);
return;
}
// Default behaviour
super.onReceivedError(view, errorCode, description, failingUrl);
}
嘿,为检查数据的用户提供弹出窗口。。StackOverflow链接
AndroidHive链接
我发现了为什么不处理WebView的错误回调的原因:
getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
移除后,此方法:
@Override
public void onReceivedError(android.webkit.WebView view, int errorCode, String description, String failingUrl) {
super.onReceivedError(view, errorCode, description, failingUrl);
}
再次开始工作
1.将您的错误模板保存为资产中的error.html
2.发生错误时从资产加载模板webview.loadUrl("file:///android_asset/error.html");