Android:FileObserver只监视顶层目录

根据文件,

"Each FileObserver instance monitors a single file or directory. If a directory is monitored, events will be triggered for all files and subdirectories inside the monitored directory." 

我的代码像,

  FileObserver fobsv = new FileObserver("/mnt/sdcard/") { @Override public void onEvent(int event, String path) { System.out.println(event+" "+path); } }; fobsv.startWatching(); 

但是,只有在/ mnt / sdcard /文件更改时, onEvent()才会触发。 如果我在/ mnt / sdcard / downloads /中创build一个文件,该方法不会被解雇。

代码有问题吗?

Solutions Collecting From Web of "Android:FileObserver只监视顶层目录"

根据文件

文档是不正确的,正如在这个问题中指出的那样。

代码有问题吗?

不,但FileObserver不是recursion的,尽pipe文档是相反的。

有一个开放源码的RecursiveFileObserver ,就像普通的FileObserver …我现在正在使用它,它是一个FileObserver,它对于你select的目录下的所有目录是recursion的。

就这个 :

 public class RecursiveFileObserver extends FileObserver { public static int CHANGES_ONLY = CLOSE_WRITE | MOVE_SELF | MOVED_FROM; List<SingleFileObserver> mObservers; String mPath; int mMask; public RecursiveFileObserver(String path) { this(path, ALL_EVENTS); } public RecursiveFileObserver(String path, int mask) { super(path, mask); mPath = path; mMask = mask; } @Override public void startWatching() { if (mObservers != null) return; mObservers = new ArrayList<SingleFileObserver>(); Stack<String> stack = new Stack<String>(); stack.push(mPath); while (!stack.empty()) { String parent = stack.pop(); mObservers.add(new SingleFileObserver(parent, mMask)); File path = new File(parent); File[] files = path.listFiles(); if (files == null) continue; for (int i = 0; i < files.length; ++i) { if (files[i].isDirectory() && !files[i].getName().equals(".") && !files[i].getName().equals("..")) { stack.push(files[i].getPath()); } } } for (int i = 0; i < mObservers.size(); i++) mObservers.get(i).startWatching(); } @Override public void stopWatching() { if (mObservers == null) return; for (int i = 0; i < mObservers.size(); ++i) mObservers.get(i).stopWatching(); mObservers.clear(); mObservers = null; } @Override public void onEvent(int event, String path) { } private class SingleFileObserver extends FileObserver { private String mPath; public SingleFileObserver(String path, int mask) { super(path, mask); mPath = path; } @Override public void onEvent(int event, String path) { String newPath = mPath + "/" + path; RecursiveFileObserver.this.onEvent(event, newPath); } } } 

在你的应用程序中创build一个新的类并将其复制到该应用程序中,并根据需要使用它! 投票,如果你觉得这有帮助!