我已经为一个目录注册了一个 FileObserver。
this.observer = new DirectoryObserver(requested.getAbsolutePath(),
FileObserver.CREATE | FileObserver.DELETE | FileObserver.DELETE_SELF);
this.observer.startWatching();
在 KitKat 模拟器上测试。亚行外壳:
root@generic:/sdcard # echo "test" >> test.txt //notified CREATE
root@generic:/sdcard # rm test.txt //notified DELETE
root@generic:/sdcard # mkdir test //no events received
root@generic:/sdcard # rmdir test //no events received
DirectoryObserver 供参考
private final class DirectoryObserver extends FileObserver {
private DirectoryObserver(String path, int mask) {
super(path, mask);
}
@Override
public void onEvent(int event, String pathString) {
switch (event) {
case FileObserver.DELETE_SELF:
//do stuff
break;
case FileObserver.CREATE:
case FileObserver.DELETE:
//do stuff
break;
}
}
}
来自文档
CREATE
Event type: A new file or subdirectory was created under the monitored directory
DELETE
Event type: A file was deleted from the monitored directory
所以对于 CREATE 我应该接收文件和目录,而 DELETE 只接收文件?好吧,我仍然没有收到 CREATE 的子目录。