android中FileObserver的运用


FileObserver,顾名思义,就是文件(夹)观察者,是用来监听文件(夹)的实时变化的,其底层是由Linux平台的inotify机制实现的,有兴趣的同学可以自行研究。

那么Android中FileObserver的具体用法如何呢?我首次接触是在PackageMangaerService的构造函数中,他被用来监视文件夹(data/app,system/app等),其本身也不难理解,我们只需要集成并重写几个方法就好了。

其中必须重写的有带一个String类型的构造函数已经 onEvent(int event, String path) 。

构造函数必须传入String类型的path值,也就是被监视的文件(夹)路径

onEvent方法则是在监测文件的各种变化。

FileObserver中提供了几种event值我们一起来看一下

[java]  view plain  copy
  1. /** Event type: Data was read from a file */  
  2. public static final int ACCESS = 0x00000001;  
  3. /** Event type: Data was written to a file */  
  4. public static final int MODIFY = 0x00000002;  
  5. /** Event type: Metadata (permissions, owner, timestamp) was changed explicitly */  
  6. public static final int ATTRIB = 0x00000004;  
  7. /** Event type: Someone had a file or directory open for writing, and closed it */  
  8. public static final int CLOSE_WRITE = 0x00000008;  
  9. /** Event type: Someone had a file or directory open read-only, and closed it */  
  10. public static final int CLOSE_NOWRITE = 0x00000010;  
  11. /** Event type: A file or directory was opened */  
  12. public static final int OPEN = 0x00000020;  
  13. /** Event type: A file or subdirectory was moved from the monitored directory */  
  14. public static final int MOVED_FROM = 0x00000040;  
  15. /** Event type: A file or subdirectory was moved to the monitored directory */  
  16. public static final int MOVED_TO = 0x00000080;  
  17. /** Event type: A new file or subdirectory was created under the monitored directory */  
  18. public static final int CREATE = 0x00000100;  
  19. /** Event type: A file was deleted from the monitored directory */  
  20. public static final int DELETE = 0x00000200;  
  21. /** Event type: The monitored file or directory was deleted; monitoring effectively stops */  
  22. public static final int DELETE_SELF = 0x00000400;  
  23. /** Event type: The monitored file or directory was moved; monitoring continues */  
  24. public static final int MOVE_SELF = 0x00000800;  
简单的实现方法:

[java]  view plain  copy
  1.       FileObserver fb = new FileObserver("/mnt/sdcard") {  
  2.       
  3.     @Override  
  4.     public void onEvent(int event, String path) {  
  5.        switch (event) {
                case FileObserver.MODIFY://监听修改
                Log.d("Modify", "path:" + path);
                break;
     }
  6.           
  7.     }  
  8. };  
  9. //开启监听  
  10. fb.startWatching();  
  11. //结束监听  
  12. fb.stopWatching();  

当然,遗憾的是我们只能监听指定的根目录或某个文件,并不能一次监听到他所有的子目录及文件,目前的解决办法是通过遍历将所有文件夹及文件都添加监听,可是FileObserver其实是一个线程,这样大规模的添加势必对程序消耗太大。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值