前情提要:android 調用 系統相冊 選擇圖片,並獲取返回的uri,之后如何獲取真實路徑
//判斷安卓版本 if (resultCode == RESULT_OK && data != null) { if (Build.VERSION.SDK_INT >= 19) handImage(data.getData()); else handImageLow(data); }
//安卓小於4.4的處理方法
private void handImageLow(Intent data) {
Uri uri = data.getData(); String path = getImagePath(uri, null); //展示圖片
...獲取真實路徑 path
}
//content類型的uri獲取圖片路徑的方法
private String getImagePath(Uri uri, String selection) {
String path = null; Cursor cursor = getContentResolver().query(uri, null, selection, null, null); if (cursor != null) { if (cursor.moveToFirst()) { path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA)); } cursor.close(); } return path; }
//安卓版本大於4.4的處理方法
@RequiresApi(api = Build.VERSION_CODES.KITKAT)
private void handImage(Uri uri) { String path = null; //根據不同的uri進行不同的解析 if (DocumentsContract.isDocumentUri(this, uri)) { String docId = DocumentsContract.getDocumentId(uri); if ("com.android.providers.media.documents".equals(uri.getAuthority())) { String id = docId.split(":")[1]; String selection = MediaStore.Images.Media._ID + "=" + id; path = getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection); } else if ("com.android.providers.downloads.documents".equals(uri.getAuthority())) { Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(docId)); path = getImagePath(contentUri, null); } } else if ("content".equalsIgnoreCase(uri.getScheme())) { path = getImagePath(uri, null); } else if ("file".equalsIgnoreCase(uri.getScheme())) { path = uri.getPath(); } //展示圖片
... 獲取真實路徑 path
}
時間過於久遠,忘了原地址,所以放在了文章里