android WebView 出错提示
通常我们通过webview来访问web页面都是在网络的情况下,一旦没有网络就会显示"无法找到该网页"的信息,这样会暴露我们的连接,所以我们需要一个有好的提示,并且不会暴露链接的方法。这时候WebViewClient的onReceivedError方法就派上了用场!
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" > <WebView android:id="@+id/webview" android:layout_width="fill_parent" android:layout_height="fill_parent" /> </RelativeLayout>
2、编写activity代码
public class MainActivity extends FragmentActivity { /** webview网页显示内容 */ public WebView wv; /** 网页访问出错提示 */ private String errorHtml = ""; private static final String TAG = MainActivity.class.getSimpleName(); // WebView wv = (WebView) findViewById(R.id.wv); wv.getSettings().setDefaultTextEncodingName("UTF-8"); //设置默认的显示编码 wv.getSettings().setJavaScriptEnabled(true);// 可用JS wv.setScrollBarStyle(0);// 滚动条风格,为0就是不给滚动条留空间,滚动条覆盖在网页上 wv.setWebViewClient(new MyWebViewClient() { public boolean shouldOverrideUrlLoading(final WebView view, final String url) { loadurl(view, url);// 载入网页 return true; }// 重写点击动作,用webview载入 });
errorHtml = "<html>" +
"<body>" +
"<h1>网络未连接!</h1>" +
"<p1>进行检查以确保您的设备具有信号和数据连接,稍后重新载入该网页。</p1>"+
"</body>" +
"</html>"; //这里进行无网络或错误处理,具体可以根据errorCode的值进行判断,做跟详细的处理。 wv.loadData(errorHtml, "text/html", "UTF-8"); @Override protected void onResume() { super.onResume(); Log.i(TAG, "--onResume()--"); } public class MyWebViewClient extends WebViewClient{ @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { Log.i(TAG, "-MyWebViewClient->shouldOverrideUrlLoading()--"); view.loadUrl(url); return true; } @Override public void onPageStarted(WebView view, String url, Bitmap favicon) { Log.i(TAG, "-MyWebViewClient->onPageStarted()--"); super.onPageStarted(view, url, favicon); } @Override public void onPageFinished(WebView view, String url) { Log.i(TAG, "-MyWebViewClient->onPageFinished()--"); super.onPageFinished(view, url); } @Override public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) { super.onReceivedError(view, errorCode, description, failingUrl); Log.i(TAG, "-MyWebViewClient->onReceivedError()--\n errorCode="+errorCode+" \ndescription="+description+" \nfailingUrl="+failingUrl); //这里进行无网络或错误处理,具体可以根据errorCode的值进行判断,做跟详细的处理。 view.loadData(errorHtml, "text/html", "UTF-8"); }
} }