Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete Audio From Sdcard

I'm trying to delete an audio file in the SD-card but I'm not successful

public boolean delete(String path)
{ 
   return new File(path).delete();
}

While going through posts I came across Storage Access Framework but unable to understand. Is it required for deleting files from SD-card? Moreover Can I only use Content Resolver to delete Files Like this?

getContenResolver().delete(uri,null,null);

Or is there any other method for deleting Audio? My app is well elevated with Write permission and Read permission and I am testing on Marshmallow 6.0

Please answer.

Thanks in advance.

like image 959
Dibyaranjan Mishra Avatar asked Sep 08 '25 03:09

Dibyaranjan Mishra


1 Answers

You need to ensure two things:

1) Since you are targeting Android.M you need to get permissions on runtime as well. Simply asking for them in the Manifest is not enough.

2) if you want to read/write data on SD card you need to use DocumentFile instead of File. The logic is more or less the same but you can refer here for more info: https://developer.android.com/reference/android/support/v4/provider/DocumentFile.html


Use this command in your OnCreate or anywhere you wish, to open a dialog that let's you select an SD directory. Select the one where your image is.

startActivityForResult(new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE), 42);

Then you will need this method as is:

@Override
    public void onActivityResult(int requestCode,int resultCode,Intent resultData) {
        if (resultCode != RESULT_OK)
            return;
        Uri treeUri = resultData.getData();
        DocumentFile pickedDir = DocumentFile.fromTreeUri(this, treeUri);
        grantUriPermission(getPackageName(), treeUri, Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
        getContentResolver().takePersistableUriPermission(treeUri, Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);

        DocumentFile YourAudioFile=  pickedDir.findFile("YourAudioFileNameGoesHere");


// And here you can delete YourAudioFile or do whatever you want with it

}
like image 170
Sotiris S. Magionas Avatar answered Sep 09 '25 17:09

Sotiris S. Magionas