我想听听文件系统中发生的变化。我正在使用 FileObserver。这是我的代码:
代码:
class MyDirObserver extends FileObserver {
String superPath;
public MyDirObserver(String path) {
super(path, ALL_EVENTS);
this.superPath = path;
}
public void onEvent(int event, String path) {
Log.e("onEvent of Directory", "=== onEvent ===");
try {
_Dump("dir", event, path, superPath);
} catch (NullPointerException ex) {
Log.e("ERROR", "I am getting error");
}
}
}
private void _Dump(final String tag, int event, String path, String superPath) {
Log.d(tag, "=== dump begin ===");
Log.d(tag, "path=" + path);
Log.d(tag, "super path=" + superPath);
Log.d(tag, "event list:");
if ((event & FileObserver.OPEN) != 0) {
Log.d(tag, " OPEN");
}
if ((event & FileObserver.CLOSE_NOWRITE) != 0) {
Log.d(tag, " CLOSE_NOWRITE");
}
if ((event & FileObserver.CLOSE_WRITE) != 0) {
Log.d(tag, " CLOSE_WRITE");
Log.i("NEWFILEOBSERVER", "File is Modified");
if (path != null) {
Log.d("---------FilePath", superPath + path);
}
}
if ((event & FileObserver.CREATE) != 0) {
isCreate = true;
Log.i("NEWFILEOBSERVER", "File is Created ");
if (path != null) {
Log.d("---------FilePath", superPath + path);
}
Log.d(tag, " CREATE");
}
if ((event & FileObserver.DELETE) != 0) {
Log.i("NEWFILEOBSERVER", "File is deleted");
if (path != null) {
Log.d("---------FilePath", superPath + path);
}
// startMyActivity("A new file is deleted thats="+superPath);
Log.d(tag, " DELETE");
}
if ((event & FileObserver.DELETE_SELF) != 0) {
Log.d(tag, " DELETE_SELF");
}
if ((event & FileObserver.ACCESS) != 0) {
Log.d(tag, " ACCESS");
}
if ((event & FileObserver.MODIFY) != 0) {
if (!isModified)
isModified = true;
if (isModified && isOpen)
isAgainModified = true;
Log.d(tag, " MODIFY");
}
if ((event & FileObserver.MOVED_FROM) != 0) {
Log.d(tag, " MOVED_FROM");
if (path != null) {
Log.d("---------FilePath", superPath + path);
}
}
if ((event & FileObserver.MOVED_TO) != 0) {
Log.d(tag, " MOVED_TO");
if (path != null) {
Log.d("---------FilePath", superPath + path);
}
}
if ((event & FileObserver.MOVE_SELF) != 0) {
Log.d(tag, " MOVE_SELF");
}
if ((event & FileObserver.ATTRIB) != 0) {
Log.d(tag, " ATTRIB");
}
Log.d(tag, "=== dump end ===");
}
它在一段时间后停止。我没有得到确切的时间,但并不总是工作,尽管我在服务中调用 startWatching() 在一个循环中为 sdcard 的所有文件夹运行并为每个文件夹调用 startWatching()。它显示出不可预测的行为并停止侦听某些文件夹并为其他文件夹完美运行。
我希望你们帮助我。我尝试了很多方法,但它并不完美。难道我做错了什么?或者有其他方法可以做到这一点。