引言
基础知识:URI与ContentResolver
在Android中,URI(Uniform Resource Identifier)用于标识资源的位置。对于存储在设备上的文件,URI通常以content://开头,后面跟着资源的路径和ID。ContentResolver是Android中用于访问内容提供者的接口,它允许应用程序访问其他应用程序存储在内容提供者中的数据。
获取图片URI
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(intent, REQUEST_CODE_PICK_IMAGE);
在onActivityResult方法中,你可以通过以下方式获取URI:
Uri imageUri = data.getData();
获取图片真实路径
Android 9 (API 级别 28) 及以上版本
String[] projection = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(imageUri, projection, null, null, null);
if (cursor != null) {
int columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String path = cursor.getString(columnIndex);
cursor.close();
// path 现在包含了图片的真实路径
}
Android 8.0 (API 级别 26) 到 Android 9
String[] projection = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(imageUri, projection, null, null, null);
if (cursor != null) {
int columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String path = cursor.getString(columnIndex);
cursor.close();
// path 现在包含了图片的真实路径
}
Android 7.0 (API 级别 24) 到 Android 8.0
在Android 7.0到Android 8.0的系统上,可以直接通过URI获取文件路径:
File file = new File(imageUri.getPath());
Android 4.4 (API 级别 19) 到 Android 7.0
String[] projection = {MediaStore.Images.Media.DATA};
Cursor cursor = managedQuery(imageUri, projection, null, null, null);
if (cursor != null) {
int columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String path = cursor.getString(columnIndex);
cursor.close();
// path 现在包含了图片的真实路径
}