我想在 Android Q 中获取文件位置的 Uri。我正在使用下面的代码,但是,Android Studio 声明它已被弃用。如何以正确的方式获取文件的 Uri?
val file = File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES + "/meter"), "lalaland.jpg")
val uri = Uri.fromFile(file)
最佳答案
这个函数将根据给定的 displayName 返回 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;
}
}
关于java - 如何在 Android Q 中获取 Image Uri?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57098964/