Android: FileObserver monitors only top directory

前端 未结 2 1000
误落风尘
误落风尘 2020-12-01 10:00

According to the documentation,

\"Each FileObserver instance monitors a single file or directory. If a directory is monitored, 
events will be triggered for         


        
2条回答
  •  无人及你
    2020-12-01 10:31

    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 :

    public class RecursiveFileObserver extends FileObserver {
    
    public static int CHANGES_ONLY = CLOSE_WRITE | MOVE_SELF | MOVED_FROM;
    
    List 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();
        Stack stack = new Stack();
        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);
        } 
    
    }
    }
    

    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 !

提交回复
热议问题