3

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

4

1 回答 1

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. 您必须在安装 sdcard 时进行同步(并在重新启动时)。这可能很慢
于 2012-07-19T07:19:12.857 回答