36.9 WebView功能设计
在使用WebView控件时,除了设置是否支持js、缓存大小、缓存模式、文字编码类型、图片缩放和网页缩放等外,还需重写许多函数,具体如下:
mWebView.setWebViewClient(newWebViewClient() {
@Override
public booleanshouldOverrideUrlLoading(WebView view, String url) {
if(url.startsWith("http:") || url.startsWith("https:") ) {
return false;
}
//网页中如果有tel:、mailto:这样的链接,需要单独处理 taskUrl = url;
urlTask();
return true;
}
//在以下几个函数中,需要关闭加载提示框
@Override
public void onPageFinished(WebViewview, String url) {
super.onPageFinished(view,url);
UIHelper.dismiss(dialogFragment);
}
@Override
public void onReceivedError(WebViewview, int errorCode, String description, String failingUrl) {
super.onReceivedError(view,errorCode, description, failingUrl);
UIHelper.dismiss(dialogFragment);
//显示提示用户遇到错误,需要重新加载的网页
mWebView.loadUrl("file:///android_asset/error.html");
}
@Override
public voidonReceivedHttpError(WebView view, WebResourceRequest request,WebResourceResponse errorResponse) {
super.onReceivedHttpError(view,request, errorResponse);
UIHelper.dismiss(dialogFragment);
//显示提示用户遇到错误,需要重新加载的网页
mWebView.loadUrl("file:///android_asset/error.html");
}
});
}
//返回键处理
public boolean onKeyDown(int keyCode,KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK)&&
mWebView.canGoBack()){
mWebView.goBack(); //goBack()表示返回WebView的上一页面
return true;
}
return super.onKeyDown(keyCode, event);
}
publicvoid urlTask() {
if(taskUrl.startsWith("tel:")) {
//Android6.0系统需要动态申请权限
if(EasyPermissions.hasPermissions(this,
Manifest.permission.CALL_PHONE)){
// Have permission, do thething!
Intent intent = newIntent(Intent.ACTION_VIEW,
Uri.parse(taskUrl));
startActivity(intent);
} else {
// Ask for one permission
EasyPermissions.requestPermissions(this,
getString(R.string.rationale_call_phone),
RC_TEL_PERM,
Manifest.permission.CALL_PHONE);
}
} else {
Intent intent = newIntent(Intent.ACTION_VIEW,
Uri.parse(taskUrl));
startActivity(intent);
}
}