0

可能这是一个奇怪的问题,但我第一次使用 FileObserver。我写的代码是

public class FileChanges extends FileObserver {
public static int CHANGES_ONLY = CLOSE_WRITE | MOVE_SELF | MOVED_FROM;

List<SingleFileObserver> mObservers;
String mPath;
int mMask;
Context mContext;

public FileChanges(String path, Context mContext) {
    this(path, ALL_EVENTS, mContext);
    this.mContext = mContext;
}

public FileChanges(String path, int mask, Context mContext) {
    super(path, mask);
    this.mContext = mContext;
    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) {
    if (event == FileObserver.ALL_EVENTS)
        Toast.makeText(mContext, "File Event", Toast.LENGTH_SHORT).show();
}

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;
        FileChanges.this.onEvent(event, newPath);
    }
  }
}

后来在 OnCreate 函数的 MainActivity 中,我调用了以下函数。

filechanges = new FileChanges(Environment.getExternalStorageDirectory()
            .toString(), this);
filechanges.startWatching();

我不明白为什么 FileObserver 没有被触发。我也尝试过单个目录,但它不起作用。

4

1 回答 1

0

FileObserver不是递归的,文档不正确!

检查这个https://code.google.com/p/android/issues/detail?id=33659

我建议使用RecursiveFileObserver

https://github.com/owncloud/android/blob/master/src/com/owncloud/android/utils/RecursiveFileObserver.java

于 2015-05-27T18:14:11.370 回答