Android: Fileobserver Monitors Only Top Directory
According to the documentation, 'Each FileObserver instance monitors a single file or directory. If a directory is monitored, events will be triggered for all files and subdirect
Solution 1:
There is an open-source RecursiveFileObserver
that works just as the normal FileObserver
should ... I am using it currently it is what it is named , it acts as a FileObserver that is recursive for all directories beneath the directory you chose ...
Here is it :
publicclassRecursiveFileObserverextendsFileObserver {
publicstaticintCHANGES_ONLY= CLOSE_WRITE | MOVE_SELF | MOVED_FROM;
List<SingleFileObserver> mObservers;
String mPath;
int mMask;
publicRecursiveFileObserver(String path) {
this(path, ALL_EVENTS);
}
publicRecursiveFileObserver(String path, int mask) {
super(path, mask);
mPath = path;
mMask = mask;
}
@OverridepublicvoidstartWatching() {
if (mObservers != null) return;
mObservers = newArrayList<SingleFileObserver>();
Stack<String> stack = newStack<String>();
stack.push(mPath);
while (!stack.empty()) {
Stringparent= stack.pop();
mObservers.add(newSingleFileObserver(parent, mMask));
Filepath=newFile(parent);
File[] files = path.listFiles();
if (files == null) continue;
for (inti=0; i < files.length; ++i) {
if (files[i].isDirectory() && !files[i].getName().equals(".")
&& !files[i].getName().equals("..")) {
stack.push(files[i].getPath());
}
}
}
for (inti=0; i < mObservers.size(); i++)
mObservers.get(i).startWatching();
}
@OverridepublicvoidstopWatching() {
if (mObservers == null) return;
for (inti=0; i < mObservers.size(); ++i)
mObservers.get(i).stopWatching();
mObservers.clear();
mObservers = null;
}
@OverridepublicvoidonEvent(int event, String path) {
}
privateclassSingleFileObserverextendsFileObserver {
private String mPath;
publicSingleFileObserver(String path, int mask) {
super(path, mask);
mPath = path;
}
@OverridepublicvoidonEvent(int event, String path) {
StringnewPath= mPath + "/" + path;
RecursiveFileObserver.this.onEvent(event, newPath);
}
}
}
Make a new class in your app and copy this code to it , and use it as you like ! Vote up if you find this helpful !
Solution 2:
According to the documentation
The documentation is incorrect, as is noted in this issue.
Is there any problem with the code?
No, but FileObserver
is not recursive, despite the documentation to the contrary.
Post a Comment for "Android: Fileobserver Monitors Only Top Directory"