Can we delete an image file using MediaStore API? if yes then how

Viewed 2303

I have a requirement to delete screenshot image file after a certain time using background service in my app and it was working fine using the above method

private void deleteTheFile(String path) {
    File fdelete = new File(path);
    if (fdelete.exists()) {
        if (fdelete.delete()) {
            getApplicationContext().sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(new File(path))));
            Log.i(TAG, "deleteTheFile: file deleted");
        } else {
            Log.i(TAG, "deleteTheFile: file not dellleeettteeeddd");
        }
    }

But as everyone knows about the changes which came with android R (11) So I tried to update my app with

MANAGE_EXTERNAL_STORAGE permission

But Google rejected my update saying

Issue: Need to use Media Store API

You have requested access to All Files Access permission but it appears that your app's core feature requires access to only Media Files. With the MediaStore API, apps can contribute and access media that's available on an external storage volume without the need for the access all files permission.

Please update your app so that the feature uses Media Store APIs and remove All Files Access (MANAGE_EXTERNAL_STORAGE) permission.

But I have never worked with media store API before and I don't know can it delete an image file with it, because deleting a file comes under writeable section

1 Answers

Using createDeleteRequest

private fun deleteImages(uris: List<Uri>) {
  val pendingIntent = MediaStore.createDeleteRequest(contentResolver, uris.filter {
    checkUriPermission(it, Binder.getCallingPid(), Binder.getCallingUid(), Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != PackageManager.PERMISSION_GRANTED
  })
  startIntentSenderForResult(pendingIntent.intentSender, REQ_CODE, null, 0, 0, 0)
}

using contentResolver

// Remove a specific media item.
val resolver = applicationContext.contentResolver

// URI of the image to remove.
val imageUri = "..."

// WHERE clause.
val selection = "..."
val selectionArgs = "..."

// Perform the actual removal.
val numImagesRemoved = resolver.delete(
        imageUri,
        selection,
        selectionArgs)

https://github.com/android/storage-samples/tree/main/MediaStore

This is an android official sample you can follow to have an understanding and try to implement it using MediaStoreAPI

Related