FileObserver change not working

This is my code:

public class SyncNotifyService extends Service { private final static String TAG = "FileService"; SDCardListener fileObserver = null; @Override public IBinder onBind(Intent intent) { return null; } public File getCacheDir() { if (!StorageUtil.isExternalStorageAvailable()) { return null; } File dir = new File(Environment.getExternalStorageDirectory(), "Cache"); return dir; } @Override public void onCreate() { super.onCreate(); Log.d(TAG, "onCreate"); fileObserver = new SDCardListener(FileCache.getCacheDir().getPath(), FileObserver.MODIFY); fileObserver.startWatching(); } class SDCardListener extends FileObserver { public SDCardListener(String path, int mask) { super(path, mask); } @Override public void onEvent(int event, String path) { final int action = event & FileObserver.ALL_EVENTS; switch (action) { case FileObserver.MODIFY: Log.d(TAG, "event: MODIFY"); break; } } } 

}

hi, I use this code to notify the directory. but I found that it never calls onEvent to use FileObserver.MODIFY param, does anyone know how to write the correct code? my version of Android 4.1.1

+4
source share
3 answers

Maybe your way of writing your onEvent doesn't work, use

 if (!event.equals(MODIFY)) { return;} //the code you want if (path.equals(blah blah blah)) { //some code.. } 

This is how I use FileObserver, I'll try ...

0
source

When creating FileObserver, the path must be absolute for the directory in which the file you are observing is located:

 fileObserver = new SDCardListener(FileCache.getCacheDir().getAbsolutePath(), FileObserver.MODIFY); 

Also change this:

  public void onEvent(int event, String path) { switch (action) { case FileObserver.MODIFY: Log.d(TAG, "event: MODIFY"); break; } } 

If onEvent does not start, try changing the initialization method of FileObserver so that it lists ALL_EVENTS and prints an event that is a trigger. Then you can understand why MODIFY is not a trigger.

0
source

Source: https://habr.com/ru/post/1483795/


All Articles