Can't delete file in Android

雨燕双飞 提交于 2019-12-08 11:00:12

问题


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


来源:https://stackoverflow.com/questions/26518368/cant-delete-file-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!