Home > Software engineering >  How to delete audio file without using "MANAGE_EXTERNAL_STORAGE" permission Android 11
How to delete audio file without using "MANAGE_EXTERNAL_STORAGE" permission Android 11

Time:01-14

How to delete audio file without using "MANAGE_EXTERNAL_STORAGE" permission on my music player app Android 11

Like this

CodePudding user response:

This depends on where the audio file is present.

  1. if the file is present in the application data directory /data/data//files then no permission is required to delete the file

  2. if the file is part of External storage, then only the files under the directory returned by getExternalFilesDir can be deleted without any permission. From Android API level 19, access to any files under folder returned by getExternalFilesDir does not require permission.

Please specify the path of the audio file if it is not both of the above cases.

CodePudding user response:

We normally delete a file using file.delete(); (or) ContentResolver.delete() (or) do a media scan on the deleted file which would remove it's entry in MediaStore.

this is we used to below Android 11 os; And would still work the same in Android 10 as well if you had opted out of scoped storage by specifying it in manifest android:requestLegacyExternalStorage="true";

Now in Android 11 you are forced to use scoped storage. If you want to delete any media file which is not created by you, you have to get the permission from the user. You can get the permission using MediaStore.createDeleteRequest(). This will show a dialog what operation users are about to perform, once the permission is granted, android has an internal code to take care of deleting both the physical file and the entry in MediaStore.

private void requestDeletePermission(List<Uri> uriList){
  if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.R) {
      PendingIntent pi = MediaStore.createDeleteRequest(mActivity.getContentResolver(), uriList);

      try {
         startIntentSenderForResult(pi.getIntentSender(), REQUEST_PERM_DELETE, null, 0, 0,
                  0);
      } catch (SendIntentException e) { }
    }
}

The above code would do both, requesting the permission to delete, and once permission granted delete the files as well.

And the callback result you would get it in onActivityResult()

  •  Tags:  
  • Related