5

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 a dir. but i found it never call onEvent use FileObserver.MODIFY param, somebody know how to write the right code? my android version is 4.1.1

Jorgesys
  • 114,263
  • 22
  • 306
  • 247

3 Answers3

0

Maybe your way in writing your onEvent isn't proper, use

if (!event.equals(MODIFY)) { return;} 

//the code you want 
if (path.equals(blah blah blah)) {
//some code.. 
}

This is the way i use in FileObserver, try it...

Seaskyways
  • 2,932
  • 3
  • 21
  • 37
0

When you create the FileObserver the path should be absolute to the directory containing the file that you are observing:

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 is not triggered, try to change how you initialize the FileObserver so that it listents to ALL_EVENTS and print the event that is trigger. Then you can figure out why MODIFY is not trigger.

Jorge
  • 1,205
  • 9
  • 19
0

The FileObserver is not recursive at all!

check this:

https://code.google.com/p/android/issues/detail?id=33659

I suggest the use of RecursiveFileObserver class:

https://github.com/owncloud/android/blob/master/src/com/owncloud/android/utils/RecursiveFileObserver.java

Jorgesys
  • 114,263
  • 22
  • 306
  • 247