Android的WebView載入網頁的幾種方式及網路異常處理
1.載入本地assert目錄下檔案(error.html)
webcontent.loadUrl(" file:///android_asset/error.html ");
2.載入網路url(http://www.csdn.com)
webcontent.loadUrl(" http://www.csdn.com ");
3.載入 String 型別html
String errorHtml = "<html><body><h1>Page not find!</h1></body></html>";
webcontent.loadData(errorHtml,
"text/html", "UTF-8");
4.載入SD卡html:
webcontent.loadUrl(" content://com.android.htmlfileprovider/sdcard/kris.html ");
異常處理:
webcontent.setWebViewClient(new WebViewClient(){
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// TODO Auto-generated method stub
Log.i("webview", "url = "+url);
view.loadUrl(url);
return true;
}
@Override
public void onReceivedError(WebView view, int errorCode,
String description, String failingUrl) {
super.onReceivedError(view, errorCode, description, failingUrl);
//這裡進行無網路或錯誤處理,具體可以根據errorCode的值進行判斷,做跟詳細的處理。
view.loadUrl(file:///android_asset/error.html
}
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
Log.i("onPageStarted", url);
super.onPageStarted(view, url, favicon);
}
@Override
public void onPageFinished(WebView view, String url) {
Log.i("onPageFinished", url);
super.onPageFinished(view, url);
}
});