1, Use class FileObserver to implement this feature
// Public Constructors
public FileObserver(String path);
public FileObserver(String path, int mask);
// Public Methods
public abstract void onEvent(int event, String path);
public void startWatching();
public void stopWatching();
2, Sample
public void onCreate(Bundle savedInstanceState)
{
...
m_myDirObsv.startWatching();
m_myFileObsv.startWatching();
}
public void onDestroy()
{
m_myDirObsv.stopWatching();
m_myFileObsv.stopWatching();
super.onDestroy();
}
private MyDirObserver m_myDirObsv = new MyDirObserver();
private MyFileObserver m_myFileObsv = new MyFileObserver();
class MyDirObserver extends FileObserver
{
public MyDirObserver()
{
super("/sdcard/sam/", ALL_EVENTS);
}
public void onEvent(int event, String path)
{
_Dump("dir", event, path);
}
}
class MyFileObserver extends FileObserver
{
public MyFileObserver()
{
super("/sdcard/sam/test.txt", ALL_EVENTS);
}
public void onEvent(int event, String path)
{
_Dump("file", event, path);
}
}
private void _Dump(String tag, int event, String path)
{
Log.d(tag, "=== dump begin ===");
Log.d(tag, "path=" + path);
Log.d(tag, "event list:");
if ((event & FileObserver.OPEN) != 0)
Log.d(tag, " OPEN");
if ((event & FileObserver.CLOSE_NOWRITE) != 0)
Log.d(tag, " CLOSE_NOWRITE");
if ((event & FileObserver.CLOSE_WRITE) != 0)
Log.d(tag, " CLOSE_WRITE");
if ((event & FileObserver.CREATE) != 0)
Log.d(tag, " CREATE");
if ((event & FileObserver.DELETE) != 0)
Log.d(tag, " DELETE");
if ((event & FileObserver.DELETE_SELF) != 0)
Log.d(tag, " DELETE_SELF");
if ((event & FileObserver.ACCESS) != 0)
Log.d(tag, " ACCESS");
if ((event & FileObserver.MODIFY) != 0)
Log.d(tag, " MODIFY");
if ((event & FileObserver.MOVED_FROM) != 0)
Log.d(tag, " MOVED_FROM");
if ((event & FileObserver.MOVED_TO) != 0)
Log.d(tag, " MOVED_TO");
if ((event & FileObserver.MOVE_SELF) != 0)
Log.d(tag, " MOVE_SELF");
if ((event & FileObserver.ATTRIB) != 0)
Log.d(tag, " ATTRIB");
Log.d(tag, "=== dump end ===");
3, WARNING: Please don't access file under busybox shell, otherwise, the observer is not triggered normally
From: http://ysl-paradise.blogspot.com/2009/02/fileobserver.html
阅读(1959) | 评论(0) | 转发(0) |