访问由我的应用程序创建的文件

Access files that were created by my application

我正在使用 MediaStore 在 Android 上创建文件,然后我需要访问它们进行阅读。我该怎么做?

有没有办法查询我所有的文件,或者通过应用程序所有者通过 ContentResolver 以某种方式过滤它们,或者我可以在创建时标记我的文件以便稍后通过这个标记过滤它们?


我的代码:

val resolver: ContentResolver = /* Is passed as an argument */
val collection = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
    MediaStore.Audio.Media.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY)
} else MediaStore.Audio.Media.EXTERNAL_CONTENT_URI

fun createFile(): Uri? {
    val fileDetails = ContentValues().apply {
        put(MediaStore.Audio.Media.DISPLAY_NAME, "example.aac")
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q)
            put(MediaStore.Audio.Media.IS_PENDING, 1)
    }

    return resolver.insert(collection, fileDetails)
}

/* Between calling these two functions I also set `IS_PENDING` to 0 */

fun findRecordings(): List<MyFile> {
    val projection = arrayOf(
        MediaStore.Audio.Media._ID,
        /* ... */
    )
    val selection = /* Filter to only get the files created by my app */
    val selectionArgs = /* ... */
    val sortOrder = /* ... */

    val files = mutableListOf<MyFile>()

    resolver.query(collection, projection, selection, selectionArgs, sortOrder)?.use { cursor ->
        val idColumn = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media._ID)
        /* Other columns */

        while (cursor.moveToNext()) {
            val id = cursor.getLong(idColumn)
            /* Other data */

            val uri = ContentUris.withAppendedId(collection, id)

            files += MyFile(uri, /* ... */)
        }
    }

    return files
}

解决方案是创建一个子文件夹并将我的文件保存在那里。为此,我在 >= Build.VERSION_CODES.Q 上使用了 MediaStore.Audio.Media.RELATIVE_PATH,在其他版本的 Android 上使用了 MediaStore.Audio.Media.DATA