Delete Audio From Sdcard

前端 未结 1 2012
暖寄归人
暖寄归人 2021-01-14 21:57

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();
}
         


        
相关标签:
1条回答
  • 2021-01-14 22:13

    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
    
    }
    
    0 讨论(0)
提交回复
热议问题