With the newer Android Q many things changed, especially with scoped storage and gradual deprecation of file:///
URIs. The problem is the lack of documentation on how to handle media files correctly on Android Q devices.
I have a media file (audio) management application and I could not find yet a reliable way to tell to the OS that I performed a change to a file so that it can update its MediaStore record.
Option #1: MediaScannerService
MediaScannerConnection.scanFile(context, new String[]{ filePath }, new String[]{"audio/*"}, new MediaScannerConnection.OnScanCompletedListener() {
@Override
public void onScanCompleted(String s, Uri uri) {
}
});
- Works with
file://
URIs from primary storage - Not works with
file://
URIs from secondary storage (such as removable storage) - Not works with any
content://
URI
Option #2: broadcast
context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri));
- Not working at all
- Soon deprecated
Option #3: manual MediaStore insertion
AudioFileContentValues
are some column values from MediaStore.Audio.AudioColumns
.
Old method based on file://
URI:
Uri uri = MediaStore.Audio.Media.getContentUriForPath(file_path);
newUri = context.getContentResolver().insert(uri, AudioFileContentValues);
MediaStore.Audio.Media.getContentUriForPath
is deprecated- Still not working
Newer method based on what I could put together from documentation:
Uri collection = MediaStore.Audio.Media.getContentUri(correctVolume);
newUri = context.getContentResolver().insert(collection, AudioFileContentValues);
Where correctVolume
would be external
from primary storage, while it would be something like 0000-0000
for secondary storage, depending on where the file is located.
- Insertion returns a content URI such as
content://media/external/audio/media/125
but then no record is persisted inside MediaStore for files located in primary storage - Insertion fails with no URI returned and no record in MediaStore
These are more or less all the methods available in previous Android versions but none of them now allow me to notify the system that I changed some audio file metadata and to get Android to update MediaStore records. Event though option #1 is partially working, this could never be a valuable solution because it's clearly not supporting content URIs.
Is there any reliable way to trigger media scan on Android Q, despite where the file is located? We shouldn't even care about file location, according to Google, since we will soon only use content URIs. MediaStore has always been a little frustrating in my opinion, but now the situation is pretty worse.
MediaStore
already knows about the content, I would think that you need to useupdate()
rather thaninsert()
in your Option #3.insert()
would be if you are creating a new piece of content. – Prier