3 回答
TA贡献2051条经验 获得超10个赞
对于 android Q 从共享存储访问媒体文件 为了提供更丰富的用户体验,许多应用程序允许用户贡献和访问外部存储卷上可用的媒体。该框架为媒体集合提供了一个优化的索引,称为媒体存储,可以更轻松地检索和更新这些媒体文件。作用域存储 android 作用域存储 android 添加一个项目到集合
public static Uri getImageContentUri(Context context, File imageFile) {
String filePath = imageFile.getAbsolutePath();
Cursor cursor = context.getContentResolver().query(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
new String[]{MediaStore.Images.Media._ID},
MediaStore.Images.Media.DATA + "=? ",
new String[]{filePath}, null);
if (cursor != null && cursor.moveToFirst()) {
int id = cursor.getInt(cursor.getColumnIndex(MediaStore.MediaColumns._ID));
cursor.close();
return Uri.withAppendedPath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "" + id);
} else {
if (imageFile.exists()) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
ContentResolver resolver = context.getContentResolver();
Uri picCollection = MediaStore.Images.Media
.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY);
ContentValues picDetail = new ContentValues();
picDetail.put(MediaStore.Images.Media.DISPLAY_NAME, imageFile.getName());
picDetail.put(MediaStore.Images.Media.MIME_TYPE, "image/jpg");
picDetail.put(MediaStore.Images.Media.RELATIVE_PATH,"DCIM/" + UUID.randomUUID().toString());
picDetail.put(MediaStore.Images.Media.IS_PENDING,1);
Uri finaluri = resolver.insert(picCollection, picDetail);
picDetail.clear();
picDetail.put(MediaStore.Images.Media.IS_PENDING, 0);
resolver.update(picCollection, picDetail, null, null);
return finaluri;
}else {
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.DATA, filePath);
return context.getContentResolver().insert(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
}
} else {
return null;
}
}
}
TA贡献1942条经验 获得超3个赞
此函数将根据给定的文件显示名称返回 Uri。您可以将其更新为 Image 之类的MediaStore.Images....
public static Uri getUriFromDisplayName(Context context, String displayName) {
String[] projection;
projection = new String[]{MediaStore.Files.FileColumns._ID};
// TODO This will break if we have no matching item in the MediaStore.
Cursor cursor = context.getContentResolver().query(extUri, projection,
MediaStore.Files.FileColumns.DISPLAY_NAME + " LIKE ?", new String[]{displayName}, null);
assert cursor != null;
cursor.moveToFirst();
if (cursor.getCount() > 0) {
int columnIndex = cursor.getColumnIndex(projection[0]);
long fileId = cursor.getLong(columnIndex);
cursor.close();
return Uri.parse(extUri.toString() + "/" + fileId);
} else {
return null;
}
}
TA贡献1836条经验 获得超13个赞
该方法Environment#getExternalStoragePublicDirectory(String)已被弃用,以提高用户隐私。如果您引用了Context(say, ctx),您可以执行以下操作:
val file = File(ctx.getExternalFilesDir(Environment.DIRECTORY_PICTURES),
"meter/lalaland.jpg")
val uri = Uri.fromFile(file)
添加回答
举报