关于小米手机调用系统相册崩溃的问题
最近在使用第三方聊天插件leancloud的时候,调用系统相册的图片,相同的代码。小米手机选择了图片之后,小米机会崩掉(别的机子,啥版本都没问题)。看异常信息,指示cursor.moveToFirst(),空指针异常。也就是说,cursor为空。是uri的问题,4.4之前,返回的是包含图片绝对路劲的,4.4之后,返回的不再是绝对路劲了,而是一个图片的编码。小米不论版本高低,小米机会崩掉,得到的只是一个图片编码。这时需要去转换为绝对路径,才能方便使用。解决办法:
/**
* 解决小米手机上获取图片路径为null的情况
*/
public Uri getPictureUri(android.content.Intent intent) {
Uri uri = intent.getData();
String type = intent.getType();
if (uri.getScheme().equals("file") && (type.contains("image/"))) {
String path = uri.getEncodedPath();
if (path != null) {
path = Uri.decode(path);
ContentResolver cr = getActivity().getContentResolver();
StringBuffer buff = new StringBuffer();
buff.append("(").append(MediaStore.Images.ImageColumns.DATA).append("=")
.append("'" + path + "'").append(")");
Cursor cur = cr.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
new String\[\] { MediaStore.Images.ImageColumns._ID },
buff.toString(), null, null);
int index = 0;
for (cur.moveToFirst(); !cur.isAfterLast(); cur.moveToNext()) {
index = cur.getColumnIndex(MediaStore.Images.ImageColumns._ID);
// set _id value
index = cur.getInt(index);
}
if (index == 0) {
// do nothing
} else {
Uri uri_temp = Uri
.parse("content://media/external/images/media/"
+ index);
if (uri_temp != null) {
uri = uri_temp;
}
}
}
}
return uri;
}
上我自己的代码:
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (Activity.RESULT_OK == resultCode) {
switch (requestCode) {
case REQUEST_IMAGE_CAPTURE:
sendImage(localCameraPath);
break;
case REQUEST_IMAGE_PICK:
sendImage(getRealPathFromURI(getActivity(), data.getData()));
break;
default:
break;
}
}
}
/**
* 根据 Uri 获取文件所在的位置
*
* @param context
* @param contentUri
* @return
*/
private String getRealPathFromURI(Context context, Uri contentUri) {
Cursor cursor = null;
try {
String\[\] proj = {MediaStore.Images.Media.DATA};
cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} finally {
if (cursor != null) {
cursor.close();
}
}
}
修改之后的代码:
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (Activity.RESULT_OK == resultCode) {
switch (requestCode) {
case REQUEST_IMAGE_CAPTURE:
sendImage(localCameraPath);
break;
case REQUEST_IMAGE_PICK:
// sendImage(getRealPathFromURI(getActivity(), data.getData()));
sendImage(getRealPathFromURI(getActivity(), getPictureUri(data)));
break;
default:
break;
}
}
}
将返回的地址转换为绝对路径后,无论在小米手机还是在其他机型都么有任何问题,第一次写博客,写的不好,大家交流,多多吐槽