I am using MediaStore
to create files on Android, then I need to access them for reading. How can I do this?
Is there a way to query all my files, or filter them by application owner through ContentResolver
somehow, or maybe I can mark my files at the creation time to filter them by this mark later?
My code:
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
}
CodePudding user response:
The solution was to create a subfolder and save my files there. For that I used MediaStore.Audio.Media.RELATIVE_PATH
on >= Build.VERSION_CODES.Q
and MediaStore.Audio.Media.DATA
on other version of Android.