How can I notify my application that one file was deleted from the SDCard (Android)?

后端 未结 1 801
野性不改
野性不改 2020-12-16 09:14

I am saving a few songs in a playlist (in my application database). When a particular song is deleted from the SDCard which already exists in the playlist, how can I reflect

相关标签:
1条回答
  • 2020-12-16 09:37

    Look into using a FileObserver

    You can monitor either a single file or directory. So what you'll have to do is determine which directories you have songs in and monitor each. Otherwise you can monitor your external storage directory and then each time anything changes, check if its one of the files in your db.

    It works real simple, something like this should work:

    import android.os.FileObserver;
    public class SongDeletedFileObserver extends FileObserver {
        public String absolutePath;
        public MyFileObserver(String path) {
            //not sure if you need ALL_EVENTS but it was the only one in the doc listed as a MASK
            super(path, FileObserver.ALL_EVENTS);
            absolutePath = path;
        }
        @Override
        public void onEvent(int event, String path) {
            if (path == null) {
                return;
            }
            //a new file or subdirectory was created under the monitored directory
            if ((FileObserver.DELETE & event)!=0) {
                //handle deleted file
            }
    
            //data was written to a file
            if ((FileObserver.MODIFY & event)!=0) {
                //handle modified file (maybe id3 info changed?)
            }
    
            //the monitored file or directory was deleted, monitoring effectively stops
            if ((FileObserver.DELETE_SELF & event)!=0) {
               //handle when the whole directory being monitored is deleted
            }
    
            //a file or directory was opened
            if ((FileObserver.MOVED_TO & event)!=0) {
               //handle moved file
            }
    
            //a file or subdirectory was moved from the monitored directory
            if ((FileObserver.MOVED_FROM & event)!=0) {
                //?
            }
    
            //the monitored file or directory was moved; monitoring continues
            if ((FileObserver.MOVE_SELF & event)!=0) {
                //?
            }
    
        }
    }
    

    Then of course you need to have this FileObserver running at all times for it to be effective so you need to put it in a service. From the service you would do

    SongDeletedFileObserver fileOb = new SongDeletedFileObserver(Environment.getExternalStorageDirectory());
    

    There are some tricky things to this that you have to keep in mind:

    1. This will drain battery worse if you have it running all the time..
    2. You'll have to synchronize when the sdcard is mounted (and on reboot). This could be slow
    0 讨论(0)
提交回复
热议问题