用miui系统上传图片的时候,会碰到从相册获取图片返回的图片为null,解决方法:
/**
* 从相册中添加
*/
private void AddPhoto(){
mCameraName = "";
photoPath = "";
Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
((Activity)context).startActivityForResult(intent, PHOTO_ZOOM);
}
/**
* 拍照添加
*/
private void AddCamera(){
String state = Environment.getExternalStorageState();
if(state.equals(Environment.MEDIA_MOUNTED)) {
mCameraName = "Camera"+System.currentTimeMillis()+".jpg";
Uri imageUri = Uri.fromFile(new File(Environment.getExternalStorageDirectory(),mCameraName));
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
//指定照片保存路径(SD卡)
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
((Activity)context).startActivityForResult(intent, PHOTO_GRAPH);
}
else {
ToastUtils.showToast(context, "请确认已插入内存卡!");
}
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == 0) {
return ;
}
// 拍照回调 PHOTO_GRAPH为启动拍照的请求码
if (requestCode == PHOTO_GRAPH) {
/**
* 获取拍照的图片
*/
photoPath = Environment.getExternalStorageDirectory() + "/" + mCameraName;
//做后续操作
}
//读取相册图片 PHOTO_ZOOM为启动相册选取的请求码
if (requestCode == PHOTO_ZOOM && (data != null && data.getData() != null)) {
Uri uri = data.getData();
uri = geturi(data);//解决方案
String[] proj = {MediaStore.Images.Media.DATA};
Cursor cursor = ((Activity)context).managedQuery(uri, proj, null, null, null);
if (cursor != null) {
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String path = cursor.getString(column_index);// 图片的路径
//path 路径有了,下面操作....
}
}
}
/**
* 解决小米手机上获取图片路径为null的情况
* @param intent
* @return
*/
public Uri geturi(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 = context.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;
}
ok,这样就解决了