Created
March 20, 2018 03:07
-
-
Save Sunzxyong/325e23e1e488e83a3509ea6cf84c593b to your computer and use it in GitHub Desktop.
recursive file observer.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import android.os.FileObserver; | |
import java.io.File; | |
import java.util.ArrayList; | |
import java.util.List; | |
import java.util.Stack; | |
/** | |
* Created by zhengxiaoyong on 2018/3/20. | |
*/ | |
public abstract class RecursiveFileObserver extends FileObserver { | |
private List<SingleFileObserver> mFileObservers; | |
private String mPath; | |
private 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 synchronized void startWatching() { | |
if (mFileObservers != null) | |
return; | |
mFileObservers = new ArrayList<>(); | |
Stack<String> stack = new Stack<>(); | |
stack.push(mPath); | |
File file; | |
String path; | |
File[] files; | |
while (!stack.empty()) { | |
path = stack.pop(); | |
mFileObservers.add(new SingleFileObserver(path, mMask)); | |
file = new File(path); | |
files = file.listFiles(); | |
if (files == null) | |
continue; | |
for (int i = 0; i < files.length; i++) { | |
if (files[i] == null) | |
continue; | |
if (files[i].isDirectory() | |
&& files[i].exists() | |
&& !files[i].getName().equals(".") | |
&& !files[i].getName().equals("..")) { | |
stack.push(files[i].getPath()); | |
} | |
} | |
} | |
for (int i = 0; i < mFileObservers.size(); i++) { | |
mFileObservers.get(i).startWatching(); | |
} | |
} | |
@Override | |
public synchronized void stopWatching() { | |
if (mFileObservers == null) | |
return; | |
for (int i = 0; i < mFileObservers.size(); i++) { | |
mFileObservers.get(i).stopWatching(); | |
} | |
mFileObservers.clear(); | |
mFileObservers = null; | |
} | |
private final class SingleFileObserver extends FileObserver { | |
private String mPath; | |
SingleFileObserver(String path, int mask) { | |
super(path, mask); | |
mPath = path; | |
} | |
@Override | |
public void onEvent(int event, String path) { | |
String finalPath = mPath + "/" + path; | |
RecursiveFileObserver.this.onEvent(event, finalPath); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment