gpt4 book ai didi

Android:FileObserver 只监控顶级目录

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:31:29 24 4
gpt4 key购买 nike

根据文档,

"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();

但是,onEvent() 仅在 /mnt/sdcard/ 中的文件发生更改时触发。如果我在 /mnt/sdcard/downloads/ 中创建文件,则不会触发该方法。

代码有问题吗?

最佳答案

有一个开源的 RecursiveFileObserver 可以像普通的 FileObserver 一样工作......我目前正在使用它,它就是它的名字,它作为一个 FileObserver,它对您选择的目录下的所有目录都是递归的...

这是它:

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);
}

}
}

在您的应用中创建一个新类并将此代码复制到其中,然后随意使用它!如果您觉得这有帮助,请投票!

关于Android:FileObserver 只监控顶级目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16448002/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com