WebView中打开手机相机进行录像打开一次后返回点击第二次失效
WebChromeClient中操作
- 重写openFileChooser(5.0以下)
- 重写onShowFileChooser(5.0以上)
public void openFileChooser(ValueCallback<Uri> filePathsCallback) {
this.openFileChooser(filePathsCallback, "*/*");
}
public void openFileChooser( ValueCallback<Uri> filePathsCallback, String acceptType ) {
this.openFileChooser(filePathsCallback, acceptType, null);
}
//@Override
public void openFileChooser(ValueCallback<Uri> filePathsCallback, String acceptType, String capture) {
this.filePathsCallback = filePathsCallback;
showFileChooserDialog(acceptType.contains("video") ? MediaStore.ACTION_VIDEO_CAPTURE : MediaStore.ACTION_IMAGE_CAPTURE);
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
@Override
public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathsCallbacks, final FileChooserParams fileChooserParams) {
this.filePathsCallbacks = filePathsCallbacks;
boolean hasVideo = false;
for (String acceptType : fileChooserParams.getAcceptTypes()) {
if (acceptType.contains("video")) hasVideo = true;
}
showFileChooserDialog(hasVideo ? MediaStore.ACTION_VIDEO_CAPTURE : MediaStore.ACTION_IMAGE_CAPTURE);
return true;
}
/**
* 根据类型打开不同的界面
* @param type 类型
*/
private void showFileChooserDialog(String type){
Intent intent = new Intent();
intent.setAction(type);
intent.addCategory(Intent.CATEGORY_DEFAULT);
FileUtils.deleteFile(new File(systemCameraPicPath));
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(systemCameraPicPath)));
curActivity.startActivityForResult(intent, 308);
}
onActivityResult回调
if (null == myCameraWebChromeClient.getFilePathsCallback() && null == myCameraWebChromeClient.getFilePathsCallbacks()) return;
Uri result = intent == null || resultCode != RESULT_OK ? null : intent.getData();
if (myCameraWebChromeClient.getFilePathsCallbacks() != null) { // 5.0 以上
onActivityResultAboveL(requestCode, resultCode, intent);
} else if (myCameraWebChromeClient.getFilePathsCallback() != null) { // 5.0 以下
myCameraWebChromeClient.getFilePathsCallback().onReceiveValue(result);
myCameraWebChromeClient.setFilePathsCallback(null);
}
Android 5.0以下
myCameraWebChromeClient.getFilePathsCallback().onReceiveValue(result);
myCameraWebChromeClient.setFilePathsCallback(null);
Android 5.0以上onActivityResult回调
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private void onActivityResultAboveL(int requestCode, int resultCode, Intent data) {
Uri[] results = null;
if (resultCode == RESULT_OK) {
if (data == null) {
} else {
String dataString = data.getDataString();
ClipData clipData = data.getClipData();
if (clipData != null) {
results = new Uri[clipData.getItemCount()];
for (int i = 0; i < clipData.getItemCount(); i++) {
ClipData.Item item = clipData.getItemAt(i);
results[i] = item.getUri();
}
}
if (dataString != null)
results = new Uri[]{Uri.parse(dataString)};
}
}
myCameraWebChromeClient.getFilePathsCallbacks().onReceiveValue(results);
myCameraWebChromeClient.setFilePathsCallbacks(null);
}