Question relevant to Android platforms API 30 to 35, app is targeting api 33
My android application’s job is to synchronize users music library on a computer to android. That includes addition of media such as music, videos to android as well as deletion.
Addition and deletion works when app is installed, however on reinstall, app can add additional files during sync but if items need to be removed because user removed media from its library in computer it is failing. MediaItems can not be removed in android. There are several dozens of files that need adding or removing, sometimes 100s. The functions of addition and removal are below.
I understand that since api 29/30 if app is reinstalled it loses ownership of it’s files. But it makes no sense when user reinstalls the app, all the previously stored content is ignored and new directory is used to resync, How to solve this problem, what is the best solution.
void addAudioToMediaStore(InputStream inStream) {
// Code to an audio media to mediastore
Uri audioCollection = MediaStore.Audio.Media
.getContentUri(MediaStor
ContentValues songDetails = new ContentValues();
songDetails.put(MediaStore.Audio.Media.DISPLAY_NAME,
filename);
songDetails.put(MediaStore.Audio.Media.RELATIVE_PATH,
String.format("Music/Library/%s/%s/",artist,album));
songDetails.put(MediaStore.Audio.Media.IS_PENDING, 1);
Uri songContentUri = resolver
.insert(audioCollection, songDetails);
byte[] buffer = new byte[1024 * 250];
long nTotalBytes = 0;
try
{
OutputStream os = resolver.openOutputStream(songContentUri, "rw");
while (nTotalBytes != size)
{
int nRead = inStream.read(buffer, 0, buffer.length);
if (nRead >= 0) {
os.write(buffer, 0, nRead);
nTotalBytes += nRead;
} else {
Log.d("TEST API 30-35 MEDIASTORE", String.format("Warning() read returned -1"));
break;
}
}
os.flush();
os.close();
} catch (Exception e) {
throw new RuntimeException(e);
}finally {
return false;
}
songDetails.clear();
songDetails.put(MediaStore.Audio.Media.IS_PENDING, 0);
int result = resolver.update(songContentUri, songDetails, null, null);
return true;
}
and delete works like this
public int deleteMediaStoreRecords(String artist, String album, String filename) {
Uri audioCollection = MediaStore.Audio.Media
.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY);
String relativePath = "%Library/"+artist+"/"+album+"%";
String selection = MediaStore.Audio.Media.DISPLAY_NAME + " LIKE ?" + " AND " + MediaStore.Audio.Media.RELATIVE_PATH + " LIKE ?" ;
// TODO This will break if we have no matching item in the MediaStore.
int numDeleted = context.getContentResolver().delete(audioCollection,
selection,
new String[]{filename,relativePath}
);
return numDeleted;
}
Query mediaStore for files, find your files and request delete
createDeleteRequest