如何通知我的应用程序从SD卡(Android)删除了一个文件?


问题内容

我正在将几首歌曲保存在播放列表中(在我的应用程序数据库中)。当从播放列表中已经存在的SDCard中删除特定歌曲时,如何反映数据库中的更改?


问题答案:

调查使用FileObserver

您可以监视单个文件或目录。因此,您要做的就是确定其中包含歌曲的目录并监视每个目录。否则,您可以监视外部存储目录,然后每次更改任何内容时,请检查其是否在数据库中。

它实际上非常简单,类似这样的方法应该起作用:

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) {
            //?
        }

    }
}

然后,当然,您需要始终运行此FileObserver才能使其生效,因此您需要将其放入服务中。从服务中您会做

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

您必须牢记一些棘手的事情:

  1. 如果您一直不停地运行,这将使电池消耗更糟。
  2. 挂载sdcard时(以及重新启动时),您必须进行同步。这可能很慢