FileObserver不会触发任何事件

时间:2015-01-16 08:15:37

标签: android fileobserver

可能这是一个奇怪的问题,但我第一次使用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没有被触发。我也尝试过单个目录,但它不起作用。

1 个答案:

答案 0 :(得分:0)