FileObserver,顾名思义,就是文件(夹)观察者,是用来监听文件(夹)的实时变化的,其底层是由linux平台的inotify机制实现的,有兴趣的同学可以自行研究。
那么android中FileObserver的具体用法如何呢?我首次接触是在PackageMangaerService的构造函数中,他被用来监视文件夹(data/app,system/app等),其本身也不难理解,我们只需要集成并重写几个方法就好了。
其中必须重写的有带一个String类型的构造函数已经 onEvent(int event, String path) 。
构造函数必须传入String类型的path值,也就是被监视的文件(夹)路径
onEvent方法则是在监测文件的各种变化。
FileObserver中提供了几种event值我们一起来看一下
/** Event type: Data was read from a file */
public static final int ACCESS = 0x00000001;
/** Event type: Data was written to a file */
public static final int MODIFY = 0x00000002;
/** Event type: Metadata (permissions, owner, timestamp) was changed explicitly */
public static final int ATTRIB = 0x00000004;
/** Event type: Someone had a file or directory open for writing, and closed it */
public static final int CLOSE_WRITE = 0x00000008;
/** Event type: Someone had a file or directory open read-only, and closed it */
public static final int CLOSE_NOWRITE = 0x00000010;
/** Event type: A file or directory was opened */
public static final int OPEN = 0x00000020;
/** Event type: A file or subdirectory was moved from the monitored directory */
public static final int MOVED_FROM = 0x00000040;
/** Event type: A file or subdirectory was moved to the monitored directory */
public static final int MOVED_TO = 0x00000080;
/** Event type: A new file or subdirectory was created under the monitored directory */
public static final int CREATE = 0x00000100;
/** Event type: A file was deleted from the monitored directory */
public static final int DELETE = 0x00000200;
/** Event type: The monitored file or directory was deleted; monitoring effectively stops */
public static final int DELETE_SELF = 0x00000400;
/** Event type: The monitored file or directory was moved; monitoring continues */
public static final int MOVE_SELF = 0x00000800;
FileObserver fb = new FileObserver("/mnt/sdcard") {
@Override
public void onEvent(int event, String path) {
// TODO Auto-generated method stub
}
};
//开启监听
fb.startWatching();
//结束监听
fb.stopWatching();
当然,遗憾的是我们只能监听指定的根目录或某个文件,并不能一次监听到他所有的子目录及文件,目前的解决办法是通过遍历将所有文件夹及文件都添加监听,可是FileObserver其实是一个线程,这样大规模的添加势必对程序消耗太大。