0

May be this is a weird question but I'm working with FileObserver first time. The code I've written is

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

And later in the MainActivity in OnCreate function I'm calling the below function.

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

I'm not getting why the FileObserver is not getting triggered. I've tried for single directory also but it's not working.

TechArcSri
  • 1,982
  • 1
  • 13
  • 20

1 Answers1

0

The FileObserver is not recursive the documentation is incorrect!

check this https://code.google.com/p/android/issues/detail?id=33659

I suggest the use of RecursiveFileObserver

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

Jorgesys
  • 124,308
  • 23
  • 334
  • 268