Reputation: 463
Inside the Android documentation for Access media files from shared storage, I found the following code snippet.
To add a media item to an existing collection, use code similar to the following. This code snippet accesses the VOLUME_EXTERNAL_PRIMARY volume on devices that run Android 10 or higher. That's because, on these devices, you can only modify the contents of a volume if it's the primary volume, as described in the Storage volumes section.
Storage volumes
Apps that target Android 10 or higher can access the unique name that the system assigns to each external storage volume. This naming system helps you efficiently organize and index content, and it gives you control over where new media files are stored.
The following volumes are particularly useful to keep in mind:
The VOLUME_EXTERNAL volume provides a view of all shared storage volumes on the device. You can read the contents of this synthetic volume, but you cannot modify the contents.
The VOLUME_EXTERNAL_PRIMARY volume represents the primary shared storage volume on the device. You can read and modify the contents of this volume.
// Add a specific media item.
val resolver = applicationContext.contentResolver
// Find all audio files on the primary external storage device.
val audioCollection =
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
MediaStore.Audio.Media.getContentUri(
MediaStore.VOLUME_EXTERNAL_PRIMARY
)
} else {
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI
}
// Publish a new song.
val newSongDetails = ContentValues().apply {
put(MediaStore.Audio.Media.DISPLAY_NAME, "My Song.mp3")
}
// Keep a handle to the new song's URI in case you need to modify it later.
val myFavoriteSongUri = resolver.insert(audioCollection, newSongDetails)
But I run the following code successfilly on device of Android API level 33
private fun testInsertByMediaStore() {
/* or MediaStore.Audio.Media.getContentUri(MediaStore.VOLUME_EXTERNAL) here */
val audioCollection = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI
val fileName = "BWF Official New Theme Song 2014 (Enhanced).mp3"
val contentValues = ContentValues().apply {
put(MediaStore.Audio.Media.DISPLAY_NAME, fileName)
put(MediaStore.Audio.Media.MIME_TYPE, "audio/mp3")
}
val uri = contentResolver.insert(
audioCollection,
contentValues,
) ?: throw Exception("Failed to create new MediaStore record.")
contentResolver.openOutputStream(uri)?.use { outputStream ->
assets.open(fileName).use { inputStream ->
var length: Int
val buffer = ByteArray(1024)
while (inputStream.read(buffer).also { length = it } != -1) {
outputStream.write(buffer, 0, length)
}
}
}
}
Didn't Google say cannot modify the contents of synthetic volume(VOLUME_EXTERNAL)?
I'm confused and headache-ridden.
If using MediaStore.Audio.Media.EXTERNAL_CONTENT_URI
works fine as before, why should use MediaStore.Audio.Media.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY)
?
Upvotes: 1
Views: 149