java - 如何在 Android Q 中获取 Image Uri?

标签 java android kotlin android-external-storage android-10.0

我想在 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/

相关文章:

java - 对 CompositeKey 使用 JoinColumn 两次获取重复列异常

java - 如何使用 shiftColumns 方法删除列

android - 在 Android Kotlin 中无法访问 dialog.getButton()

android - 启用缩小后 JsonProperty 不工作

android - PowerMockito spy : Calling real method results with CannotStubVoidMethodWithReturnValue

android - 如何检测 TextView 中的换行符

java - JAR 文件从另一个目录运行?

java - 为什么在 java 中 'joined' 线程启动之前 join() 方法之前的行不打印?

java - android.widget.textview 无法转换为 android.widget.radiogroup

android - 使用 Gradle 设置单元测试时出错