前情提要: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
}
时间过于久远,忘了原地址,所以放在了文章里