小弟原创文章,转载请注明本文出处http://www.jianshu.com/p/62f3750f72a8
前言(针对5.0以上选择图片之后闪退问题的修复)
问题描述:上篇文章中(地址:http://www.jianshu.com/p/841bfa47b45c),因手上测试机有限,没有测到一些问题,在5.0以上的机型中,选择图片点确定之后闪退。
这里对各种看众表示抱歉,特别是对那些点赞,或者用到我代码的读者,真的很抱歉!(我本意是帮助那些遇到同样问题的兄弟,不料反而坑了一把)
正题
在H5(js)页面中需要上传图片用的是input type=file的标签,当webview加载该页面,触发该标签时,会回调webView.setWebChromeClient(new WebChromeClient())中的onShowFileChooser方法(5.0之前都是openFileChooser方法)
private ValueCallback<Uri[]> uploadMessageAboveL;
// Android 5.0以上WebChromeClient中的隐藏方法
@Override
public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback,
WebChromeClient.FileChooserParams fileChooserParams ) {
if (uploadMessageAboveL != null) {
uploadMessageAboveL.onReceiveValue(null);
uploadMessageAboveL = null;
}
uploadMessageAboveL = filePathCallback;
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("image/*");
startActivityForResult(
Intent.createChooser(i, "Image Chooser"),
FILECHOOSER_RESULTCODE);
return true;
}
在当前页面在重写onActivityResult,来处理选择图片之后的回调
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == FILECHOOSER_RESULTCODE) {
if (null == uploadMessageAboveL) return;
Uri result = data == null || resultCode != RESULT_OK ? null : data.getData();
if (uploadMessageAboveL != null) {
onActivityResultAboveL(requestCode, resultCode, data);
}
}
onActivityResultAboveL方法
private void onActivityResultAboveL(int requestCode, int resultCode, Intent data) {
if (requestCode != FILECHOOSER_RESULTCODE || uploadMessageAboveL == null) {
return;
}
Uri[] results = null;
if (resultCode == Activity.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)};
}
}
}
uploadMessageAboveL.onReceiveValue(results);
uploadMessageAboveL = null;
return;
}
这样就解决了上篇博文中的bug
我用小米 max(6.01),小米6(7.0),华为荣耀4A(5.1),红米(6.01)测试过了,才敢放这段代码出来。
网友评论