android中FileObserver的运用

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其实是一个线程,这样大规模的添加势必对程序消耗太大。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值