'Android 10: Delete denied by permission:android.permission.ACCESS_MEDIA_PROVIDER

Target SDK in my project is 31 and when I'm trying to delete a file from DCIM directory, I'm getting following error such as delete denied by permission:android.permission.ACCESS_MEDIA_PROVIDER. Please consider file path like this: "/storage/emulated/0/DCIM/Screenshots/pic1.jpg"

I have tried so much to find the result every where including stack overflow, but didn't succeeded yet. Even I changed target SDK to lower 30 but not worked.

Following are the solutions that I had already worked on but nothing works:

1.flags in manifest file

android:requestLegacyExternalStorage="true"
android:preserveLegacyExternalStorage="true"

2.permissions in manifest file

<uses-permission
    android:name="android.permission.WRITE_EXTERNAL_STORAGE"
    android:maxSdkVersion="40"
    tools:replace="android:maxSdkVersion" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission
    android:name="android.permission.MANAGE_EXTERNAL_STORAGE"
    tools:ignore="ScopedStorage" />

Please find the attached code

val fileToDelete = File("/storage/emulated/0/DCIM/Screenshots/pic1.jpg")
fileToDelete.delete()

NOTE: filepath is hardcoded only to explain better

Please find the attached log

2022-03-21 11:22:35.331 8639-20226/com.filepickerdemo D/ContentResolver: delete denied by permission:android.permission.ACCESS_MEDIA_PROVIDER#content://media/external/images/media#_data = ?#/storage/emulated/0/DCIM/Screenshots/pic1.jpg

What else should I put in my code to solve this issue. Thanks in advance.



Solution 1:[1]

To delete media files in android 10 and above, You can try contentresolver API.

You need to pass the media's content uri to the 'contentResolver.delete()' method & you will be able to do it easily.

Here is my post on how to do that using Java - Scoped Storage in Android — Writing & Deleting Media Files

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Dev4Life