FileObserver,顾名思义,就是文件(夹)观察者,是用来监听文件(夹)的实时变化的,其底层是由Linux平台的inotify机制实现的,有兴趣的同学可以自行研究。
那么Android中FileObserver的具体用法如何呢?我首次接触是在PackageMangaerService的构造函数中,他被用来监视文件夹(data/app,system/app等),其本身也不难理解,我们只需要集成并重写几个方法就好了。
其中必须重写的有带一个String类型的构造函数已经 onEvent(int event, String path) 。
构造函数必须传入String类型的path值,也就是被监视的文件(夹)路径
onEvent方法则是在监测文件的各种变化。
FileObserver中提供了几种event值我们一起来看一下
-
- public static final int ACCESS = 0x00000001;
-
- public static final int MODIFY = 0x00000002;
-
- public static final int ATTRIB = 0x00000004;
-
- public static final int CLOSE_WRITE = 0x00000008;
-
- public static final int CLOSE_NOWRITE = 0x00000010;
-
- public static final int OPEN = 0x00000020;
-
- public static final int MOVED_FROM = 0x00000040;
-
- public static final int MOVED_TO = 0x00000080;
-
- public static final int CREATE = 0x00000100;
-
- public static final int DELETE = 0x00000200;
-
- public static final int DELETE_SELF = 0x00000400;
-
- public static final int MOVE_SELF = 0x00000800;
简单的实现方法:
- FileObserver fb = new FileObserver("/mnt/sdcard") {
-
- @Override
- public void onEvent(int event, String path) {
- switch (event) {
case FileObserver.MODIFY://监听修改
Log.d("Modify", "path:" + path);
break;
} -
- }
- };
-
- fb.startWatching();
-
- fb.stopWatching();
当然,遗憾的是我们只能监听指定的根目录或某个文件,并不能一次监听到他所有的子目录及文件,目前的解决办法是通过遍历将所有文件夹及文件都添加监听,可是FileObserver其实是一个线程,这样大规模的添加势必对程序消耗太大。