Android 监视文件或目录变化

时间:2022-06-24 00:04:37

Android系统API提供了FileObserver抽象类(Linux的INotify机制)来监听系统/sdcard中的文件或文件夹,FileObserver类能对sdcard中的文件及文件夹的打开、创建、移动和删除操作进行监控。下面看看代码实现:


package com.orgcent.filelistener;


import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.os.FileObserver;

public class AndroidFileListenerActivity extends Activity {
private FileObserver mFileObserver;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

if(null == mFileObserver) {
mFileObserver = new SDCardFileObserver(Environment.getExternalStorageDirectory().getPath());
mFileObserver.startWatching(); //开始监听
}
}

public void onDestory() {
if(null != mFileObserver) mFileObserver.stopWatching(); //停止监听
}

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;
}
}

}
}