android webView 图片选择
一、webView 图片选择器调用触发
开发中经常会与H5 交互,遇到图片选择怎么办呢?
WebChromeClient 中 onShowFileChooser 可以用来处理图片选择问题
代码如下:
mWebView.setWebChromeClient(new WebChromeClient(){
private Uri imgUri;
@Override
public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
return true; //todo ture 处理数据
}
});
onShowFileChooser:对应了html 表单中 中 input 标签中的type= file 类型,在pc 端会触发 一个文件资源管理器,
在webView 中 则会触发 WebChromeClient 中 onShowFileChooser 方法,在该方法中我们可以调用相册选择器或者自定义的照片选择器控件
onShowFileChooser参数:
-
WebView :webView 组件
-
ValueCallback<Uri[]>
接收选择照片后uri 数组,在选择成功之后,调用 :
filePathCallback.onReceiveValue(uris);
-
FileChooserParams
系统图片选择器打开所配置的参数
onShowFileChooser 返回值:
onShowFileChooser 返回值为一个boolean 类型 true/false,默认值是false
二、图片选择回调处理
onShowFileChooser 调用图片选择器之后 必须修改默认返回值为true ,方能正确处理数据
filePathCallback 接口参数处理 :
uris = new Uri[photos.size()];
....
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { //N android 7.0
imgUri = FileProvider.getUriForFile(mRootView.getActivity(), mRootView.getActivity().getPackageName() + ".fileProvider", new File(photos.get(i).getCompressionPath()));
}
uris[i] = imgUri;
filePathCallback.onReceiveValue(uris);
return true;
处理图片选择取消回调
调用图片选择器取消之后 filePathCallback 必须传入一个null 参数 代码:
通常会在 onActivityResult 方法中处理
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(success){
photos //图片数据
}else{
filePathCallback.onReceiveValue(null);
filePathCallback = null;
}
}
三、常见问题(Exception)
showFileChooser result was already called
onShowFileChooser 返回值为 false 导致 修改为 true
java.lang.IllegalStateException: Duplicate showFileChooser result
filePathCallback.onReceiveValue() 方法连续调用两次所致