首先想到的是实现一个WebViewClient,监听里面的onreceivererror()做相应的异常处理,后面发现每次出现error之后又会有onPageStarted,onPageFinish()两次,不会在我想要处理的onreceivererror()显示我想要的异常页面:
原因可能如下(本人自己的猜测),由于webview底层的解析和webviewclient是分处在两个不同的线程,而当webview底层解析遇到问题会去显示android自身的错误界面,会走一次onPageFinish(),webviewclient会走一次OnPageStart(),,onPageFinish(),所以这个时候加载的默认界面还是webview自身的。
解决办法如下:
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
mIsLoadResource = false;
mWapLoadingView.setVisibility(View.VISIBLE);
mTitleView.startRefreshRotate();
mWapLoadFailed.setVisibility(View.GONE);
}
@Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
mWapLoadingView.setVisibility(View.GONE);
mTitleView.stopRefreshRotate();
if (!mIsLoadResource) {
mWapLoadFailed.setVisibility(View.VISIBLE);
view.stopLoading();
}
}
public void onLoadResource(WebView view, String url) {
mIsLoadResource = true;
super.onLoadResource(view, url);
}
@Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
mTitleView.stopRefreshRotate();
if (!mIsLoadResource) {
mWapLoadFailed.setVisibility(View.VISIBLE);
view.stopLoading();
}
super.onReceivedError(view, errorCode, description, failingUrl);
}
@Override
public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
handler.proceed();// 接受证书
mTitleView.stopRefreshRotate();
if (!mIsLoadResource) {
mWapLoadFailed.setVisibility(View.VISIBLE);
view.stopLoading();
}
}
t通过OnLoadResource的回调来应对错误的情况,由于webview自身加载本机的默认失败页面是不会调用onloadresource的那么就可以通过onloadresource来作为是否是加载失败的标志,从而对错误做相应的处理