Android应用开发的时候可能会用到WebView这个组件,在WebView的开发过程中当你需要使用到一些高级功能,可以通过设置WebChromeClient从而来辅助WebView处理 JavaScript 的对话框、网站图标、网站title、加载进度等。
WebChromeClient常用的API方法
1.通知应用程序当前网页加载的进度
首先在WebChormeClient中重写以下方法,通过接口mlWebpageView回调给webActivity;
@Override
public void onProgressChanged(WebView view, int newProgress) {
super.onProgressChanged(view, newProgress);
mIWebPageView.progressChanged(newProgress);
}
webActivity中实现回调方法,这里用的是先加载到90%再加载到100%, 具体为什么相信大家都懂吧...
@Override
public void progressChanged(int newProgress)
{
if (mProgress90)
{
int progress = newProgress * 100;
if (progress > 900)
{
mProgressBar.setProgress(progress);
if (progress == 1000)
{
mProgressBar.setVisibility(View.GONE);
}
}
}
}```
#####2.获取网页title标题
通过以下方法获得title回传给activity中的toolbar设置标题
```@Override
public void onReceivedTitle(WebView view, String title) {
super.onReceivedTitle(view, title);
// 设置title
mActivity.setTitle(title);
this.title = title;
}
3.网页中播放网络视频调用的方法
视频播放全屏会被调用的方法
@Override
public void onShowCustomView(View view, CustomViewCallback callback) {
}
视频播放退出全屏会被调用的方法
@Override
public void onHideCustomView() {
}
视频加载时进程loading,可在此方法中加载Progress
@Override
public View getVideoLoadingProgressView() {
if (mXProgressVideo == null) {
LayoutInflater inflater = LayoutInflater.from(mActivity);
mXProgressVideo = inflater.inflate(R.layout.video_loading_progress, null);
}
return mXProgressVideo;
}
4.从 Android 设备中选择图片和文件
在Android 5.0 API 21后 借助新的 onShowFileChooser() 方法,可以启动文件选择器从 Android 设备中选择图片和文件
// For Android > 5.0
@Override
public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> uploadMsg, FileChooserParams fileChooserParams) {
openFileChooserImplForAndroid5(uploadMsg);
return true;
}
private void openFileChooserImplForAndroid5(ValueCallback<Uri[]> uploadMsg) {
mUploadMessageForAndroid5 = uploadMsg;
Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT);
contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE);
contentSelectionIntent.setType("image/*");
Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER);
chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent);
chooserIntent.putExtra(Intent.EXTRA_TITLE, "图片选择");
mActivity.startActivityForResult(chooserIntent, FILECHOOSER_RESULTCODE_FOR_ANDROID_5);
}
onActivityResult中上传文件成功后的回调
public void mUploadMessageForAndroid5(Intent intent, int resultCode) {
if (null == mUploadMessageForAndroid5)
return;
Uri result = (intent == null || resultCode != RESULT_OK) ? null : intent.getData();
if (result != null) {
mUploadMessageForAndroid5.onReceiveValue(new Uri[]{result});
} else {
mUploadMessageForAndroid5.onReceiveValue(new Uri[]{});
}
mUploadMessageForAndroid5 = null;
}
具体实例可以参照 GoogleChrome高级使用实例[https://github.com/GoogleChrome/chromium-webview-samples]