这个问题的解决方法是在onActivityResult方法中使用手动触发的onShowFileChooser回调。解决步骤如下:
确保你添加了以下两个权限:
添加以下代码到WebChromeClient的onShowFileChooser:
ValueCallback
public boolean onShowFileChooser(WebView webView, ValueCallback
// Create camera intent
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (cameraIntent.resolveActivity(getActivity().getPackageManager()) != null) {
// Create a file to store the image
File photoFile = null;
try {
photoFile = createImageFile();
cameraIntent.putExtra("PhotoPath", mCameraPhotoPath);
} catch (IOException ex) {
// Error occurred while creating the File
Log.e(TAG, "Unable to create Image File", ex);
}
// Continue only if the File was successfully created
if (photoFile != null) {
mCameraPhotoPath = "file:" + photoFile.getAbsolutePath();
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
} else {
cameraIntent = null;
}
}
// Create file chooser intent
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("*/*");
// Create file chooser intent
Intent chooserIntent = Intent.createChooser(intent, "选择文件");
// Add the camera options
if (cameraIntent != null) {
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Intent[] { cameraIntent });
}
// Launch the file chooser
startActivityForResult(chooserIntent, INPUT_FILE_REQUEST_CODE);
return true;
}
添加以下代码到Activity的onActivityResult:
@Override public void onActivityResult (int requestCode, int resultCode, Intent data) { if (requestCode != INPUT_FILE_REQUEST_CODE || mUploadMessage == null) { super.onActivityResult(requestCode, resultCode, data); return; }
Uri[] results = null;
// Check that the response is a good one
if (resultCode == Activity.RESULT_OK) {
if (data == null) {
// If there is not data, then we may have taken a photo
if (mCameraPhotoPath != null) {
results = new Uri[] { Uri.parse(mCameraPhotoPath) };
}
} else {
String dataString = data.getDataString();
if (dataString != null) {
results = new Uri[] { Uri.parse(dataString) };
}
}
}
mUploadMessage.onReceiveValue(results);
mUploadMessage = null;
}
最后,定义输入文件请求代码。
private static final int INPUT_FILE_REQUEST_CODE = 1;
通过这些步骤,您可以成功处理Android WebView onShowFileChooser方法无法显示结果的问题。