项目内嵌webview需要进行图片选择,按常规直接给webview增加WebChromeClient。代码如下:
class MyWebChromeClient extends WebChromeClient { public void openFileChooser(ValueCallback<Uri> uploadMsg) { resetWebSelectImageCallBack(); mUploadMsg = uploadMsg; selectImage(); } public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) { resetWebSelectImageCallBack(); mUploadMsg = uploadMsg; selectImage(); } @Override public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) { resetWebSelectImageCallBack(); mUploadMsg = uploadMsg; selectImage(); } @Override public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> valueCallback, FileChooserParams fileChooserParams) { resetWebSelectImageCallBack(); mValueCallback = valueCallback; selectImage(); return true; } }
选择图片后,将数据通过回调返回webview:
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (WebViewContract.SELECT_FILE_REQ == requestCode) {
if (Activity.RESULT_OK != resultCode) {
resetWebSelectImageCallBack();
return;
}
if (null != mUploadMsg) {
mUploadMsg.onReceiveValue(UriUtils.file2Uri(new File(FileConstants.IMAGE_TEMP)));
mUploadMsg = null;
}
if (null != mValueCallback) {
mValueCallback.onReceiveValue(new Uri[]{UriUtils.file2Uri(new File(FileConstants.IMAGE_TEMP))});
mValueCallback = null;
}
}
}
选择图片没有什么好说的,但是一定注意一个点:在未成功回调数据给webview时,一定返回一个null。否则下次调用时,是无法进入方法的!
我这边的处理方法是调用resetWebSelectImageCallBack():
private void resetWebSelectImageCallBack() {
if (null != mUploadMsg) {
mUploadMsg.onReceiveValue(null);
mUploadMsg = null;
}
if (null != mValueCallback) {
mValueCallback.onReceiveValue(null);
mValueCallback = null;
}
}