1

In Android I use the FileObserver to observe a folder and do something when a new file is created.

I noticed that the CREATE event is generated on Android 5 and Android 7 but it is NOT generated on Android 8. Any idea why?

This is the pseudocode.

public class FolderObserver extends FileObserver {

   String path;
   static final int mask = (FileObserver.CREATE);

   public FolderObserver(String path) {
       super(path,mask);
       this.path = path;
   }

   void doSomeAction(string file){}

   @Override
   public void onEvent(int i, @Nullable String s) {
       switch (i) {
           case FileObserver.CREATE:
               // this event is generated on Android 5 and 7
               // but is NOT generated on Android 8
               doSomeAction(s);
               break;
           default:
               break;
       }
   }
}

....

/*
in my client
*/
FolderObserver observer = new FolderObserver(myPath);
observer.startWatching();
Klaus78
  • 11,648
  • 5
  • 32
  • 28

1 Answers1

1

Finally I found a workaround.

Copying a new file into the observed folder generates the CREATE event on Android 5 and 7 while it generates the MOVE_TO event on Android 8, strange but ok.

So I simply listen for both events like that

static final int mask = (FileObserver.CREATE | FileObserver.MOVED_TO);

....

public void onEvent(int i, @Nullable String s) {
    switch (i) {
        case FileObserver.CREATE:
        case FileObserver.MOVED_TO:
            doSomeAction(s);
            break;
        default:
            break;
    }
}
Klaus78
  • 11,648
  • 5
  • 32
  • 28