Android4.4開啟系統相簿返回Null問題
阿新 • • 發佈:2019-01-22
public interface PhotoCallBack {
void onSuccess(String picturePath);// 拿取相片成功
void onFailure();// 拿取相片失敗
}
/**
* 獲取圖片路徑
*
* @param context
* @param data
* @param callback
* @return
*/
public static void getPhotoURLByAlbum(Context context, Intent data, PhotoCallBack callback) {
if (data == null) {
callback.onFailure();
return;
}
final Uri selectedImage = data.getData();
if (selectedImage == null) {
callback.onFailure();
return;
}
String picturePath = ""; // 關於Android4.4的圖片路徑獲取,如果回來的Uri的格式有兩種
if (Build.VERSION.SDK_INT >= 19 && DocumentsContract.isDocumentUri(context, selectedImage)) {
String wholeID = DocumentsContract.getDocumentId(selectedImage);
String id = wholeID.split(":")[1];
String[] column = { MediaStore.Images.Media.DATA };
String sel = MediaStore.Images.Media._ID + "=?" ;
Cursor cursor = context.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, column, sel, new String[] { id }, null);
if (cursor.moveToNext()) {
int columnIndex = cursor.getColumnIndex(column[0]);
picturePath = cursor.getString(columnIndex);
callback.onSuccess(picturePath);// 獲取圖片路徑
}
cursor.close();
} else {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = context.getContentResolver().query(selectedImage, projection, null, null, null);
if (cursor.moveToNext()) {
int column_index = cursor.getColumnIndex(MediaStore.Images.Media.DATA);
picturePath = cursor.getString(column_index);
callback.onSuccess(picturePath);// 獲取圖片路徑
}
cursor.close();
}
}
在onActivityResult中處理返回的資料。
同時一定要在開啟相簿的邏輯中做判斷
Intent intent = new Intent();
intent.setType("image/*");// 從所有圖片中進行選擇
//根據版本號不同使用不同的Action
if (Build.VERSION.SDK_INT <19) {
intent.setAction(Intent.ACTION_GET_CONTENT);
}else {
intent.setAction(Intent.ACTION_OPEN_DOCUMENT);
}
((Activity) context).startActivityForResult(intent, Constants.REQUEST_CODE_HEADPIC_PICK_PHOTO);