Android系统API提供了FileObserver抽象类(Linux的INotify机制)来监听系统/sdcard中的文件或文件夹,FileObserver类能对sdcard中的文件及文件夹的打开、创建、移动和删除操作进行监控。下面看看代码实现:
//设置所要监控的文件或文件夹 mFileObserver = new SDCardFileObserver(Environment.getExternalStorageDirectory().getPath()); //开始监听 mFileObserver.startWatching(); static class SDCardFileObserver extends FileObserver { //mask:指定要监听的事件类型,默认为FileObserver.ALL_EVENTS public SDCardFileObserver(String path, int mask) { super(path, mask); } public SDCardFileObserver(String path) { super(path); } @Override public void onEvent(int event, String path) { final int action = event & FileObserver.ALL_EVENTS; switch (action) { case FileObserver.ACCESS: System.out.println("event: 文件或目录被访问, path: " + path); break; case FileObserver.DELETE: System.out.println("event: 文件或目录被删除, path: " + path); break; case FileObserver.OPEN: System.out.println("event: 文件或目录被打开, path: " + path); break; case FileObserver.MODIFY: System.out.println("event: 文件或目录被修改, path: " + path); break; } } }
原文地址:http://laocai.blog.51cto.com/10020033/1630049