Android WebView加载网页失败处理

xiaoxiao2021-02-28  60

WebView在加载网页的时候,如果加载失败,显示系统默认的错误页面很丑,而且很恶心,会暴露url。一般操作处理:自定义一个错误页面。这个页面可以是一个本地网页,也可以是Android页面。 技术点:重写WebViewClient里面的onReceivedError(); onReceivedError调用情况:onReceivedError只有在遇到不可用的(unrecoverable)错误时,才会被调用)。 比如,当WebView加载链接www.baidu.com时,”不可用”的情况有可以包括有: 1、没有网络连接 2、连接超时 3、找不到页面www.baidu.com 而下面的情况则不会被报告: 1、网页内引用其他资源加载错误,比如图片、css不可用 2、js执行错误 具体处理代码:

`

class MyClient extends WebViewClient { @TargetApi(Build.VERSION_CODES.LOLLIPOP) @Override //Log.e(TAG, "shouldOverrideUrlLoading: (new)-----" + String.valueOf(request.getUrl())); return false; } @Override public void onPageStarted(WebView view, String url, Bitmap favicon) { //Log.e(TAG, "onPageStarted: ----url:" + url); } @Override public void onPageFinished(WebView view, String url) { mProgressBar.setVisibility(View.GONE); if (mIsLoadSuccess) { mErrorView.setVisibility(View.GONE); mWebView.setVisibility(View.VISIBLE); //根据Url处理自己的业务 handleWebRequest(url); } else { mErrorView.setVisibility(View.VISIBLE); mWebView.setVisibility(View.GONE); } } /** * 这里进行无网络或错误处理,具体可以根据errorCode的值进行判断,做跟详细的处理。 * * @param view */ // 旧版本,会在新版本中也可能被调用,所以加上一个判断,防止重复显示 @Override public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) { super.onReceivedError(view, errorCode, description, failingUrl); //Log.e(TAG, "onReceivedError: ----url:" + error.getDescription()); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { return; } // 在这里显示自定义错误页 mErrorView.setVisibility(View.VISIBLE); mWebView.setVisibility(View.GONE); mProgressBar.setVisibility(View.GONE); mIsLoadSuccess = false; } // 新版本,只会在Android6及以上调用 @TargetApi(Build.VERSION_CODES.M) @Override public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) { super.onReceivedError(view, request, error); if (request.isForMainFrame()) { // 或者: if(request.getUrl().toString() .equals(getUrl())) // 在这里显示自定义错误页 mErrorView.setVisibility(View.VISIBLE); mWebView.setVisibility(View.GONE); mIsLoadSuccess = false; } } }`

下载链接 WebView加载网页失败处理Demo

转载请注明原文地址: https://www.6miu.com/read-53399.html

最新回复(0)