Can't delete file in Android

2019-06-09 16:19发布

问题:

I wish delete music file stored on my phone (has no SD card) in Music folder. I have file path and File.exists() said true. Next, File.delete() also said true, but file stay in its place. But! After "deletion" I can no longer play this file, edit name and also can't copy it. But I can delete it manually.

I've set android.permission.WRITE_EXTERNAL_STORAGE. OS 4.4.4 GPE

Where is my mistake? Any suggestions, thanks.

    File file = new File(Path);
    if (file.exists()){
        file.setWritable(true, false);
        return file.delete();
    }

回答1:

Windows is not looking at external storage directly. It is looking at the data served up by the Media Transfer Protocol (MTP) server on your Android device. It, in turn, is working with the MediaStore index, not the actual filesystem.

If you make any change to external storage, such as deleting a file, you need to update MediaStore. Off the cuff, I do not recall exactly how to do that for a deleted file, though I would consider trying to use MediaScannerConnection and scanFile() to perhaps scan the directory that contained the deleted file.



回答2:

So, my final solution that seems to work is:

public Boolean deleteTrack(String key){
    MusicTrack track = getAlbum(0).getTrackByKey(key);
    if (track == null) return false;

    File file = new File(track.getData().Path);
    if (file.exists()){
        file.setWritable(true, false);
        String where = MediaStore.Audio.Media.DATA +"=\""+ track.getData().Path +"\"";
        if (context.getContentResolver().delete(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, where, null) == 1){
            if (file.exists()){
                Boolean d = file.delete();
                context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(file)));
                return d;
            }
            return true;
        }
    }
    return false;
}