且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-09-28 10:15:52

考虑使用一个的 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) {
            //?
        }

    }
}

那当然,你需要有这个FileObserver在任何时候运行它,所以你需要把它放在一个服务是有效的。你会从服务做

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. 这将耗尽的电池更糟,如果你有它运行所有的时间。
  2. 您将必须同步,当SD卡安装(并重新启动)。这可能是缓慢的