如何通知我的应用程序已从SDCard(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. 安装SD卡时(以及重启时)必须同步。 这可能很慢