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

时间:2012-07-19 07:15:29

标签: java android

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

1 个答案:

答案 0 :(得分:4)

使用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. 安装SD卡时(以及重启时)必须同步。这可能很慢