在Android Web view中实现文件选择功能需要设置WebChromeClient以覆盖onShowFileChooser方法。以下是一个简单的示例代码:
public class MyWebChromeClient extends WebChromeClient {
@Override
public boolean onShowFileChooser(WebView webView, ValueCallback filePathCallback, WebChromeClient.FileChooserParams fileChooserParams) {
if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
FILE_PERMISSION_REQUEST_CODE);
return false;
}
else {
openFileChooser(webView, filePathCallback);
return true;
}
}
public void openFileChooser(WebView webView, ValueCallback filePathCallback) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("*/*");
intent.addCategory(Intent.CATEGORY_OPENABLE);
try {
startActivityForResult(Intent.createChooser(intent, "Choose File to Upload"), REQUEST_FILE_UPLOAD);
} catch (Exception ex) {
Log.e(TAG, "Exception: " + ex);
}
uploadFilePathCallback = filePathCallback;
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_FILE_UPLOAD && resultCode == RESULT_OK) {
if (uploadFilePathCallback != null) {
Uri[] uris = new Uri[]{data.getData()};
uploadFilePathCallback.onReceiveValue(uris);
}
}
}
}
在MainActivity中,将WebView设置为如下:
webView.setWebChromeClient(new MyWebChromeClient());
在这种设置后,Android WebView就可以从打开对话框中选择文件。