Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FileObserver getting strange events

Tags:

android

Ok, this is simple: I have a FileObserver class to observe a folder with music. So I implemented onEvent and all that stuff, but when I move or paste a file on that folder using a file manager, instead of getting a FileObserver.MOVED_TO or a FileObserver.CREATE, I'm getting weird events with numbers like 1073741656, that are not documented on: http://developer.android.com/reference/android/os/FileObserver.html

So how do I get those specific events like deleting, moving, creating and pasting?

[edit] Here is the code:

 private class MusicsFileObserver extends FileObserver {

    public MusicsFileObserver(String root) {
        super(root);

        if (!root.endsWith(File.separator)) {
            root += File.separator;
        }
    }

    @SuppressWarnings("unused")
    public void close() {
        super.finalize();
    }

    public void onEvent(final int event, String path) {
      //here is the problem, if you see the documentation, when a file is moved 
      //to this directory, event should be equal to FileObserver.MOVED_TO, 
      //a constant value of 128. But when debugging, instead of entering here one time
      //with event == 128, this method onEvent is being called 4~5 times with event
      //with numbers like 1073741656
        if (event != FileObserver.ACCESS || event != FileObserver.OPEN || event != 32768)
            runOnUiThread(new Runnable() {
                public void run() {
                    rescanMusics();
                }
            });
    }
}
like image 774
Paulo Cesar Avatar asked Jun 13 '11 21:06

Paulo Cesar


3 Answers

For anyone else that runs into this, I found the MOVED_TO and MOVED_FROM events have high-order bits turned on in the event flag. MOVED_FROM is 0x40000040 and MOVED_TO is 0x40000080. The workaround is to simply 'and' ALL_EVENTS with the event code to turn off the high bits, i.e. "event &= FileObserver.ALL_EVENTS"

Update: I found the inotify flags that you can get from https://asyncinotify.readthedocs.io/en/latest/doc/asyncinotify.html, it would be nice if google added these bit flags to the FileObserver doc.

like image 154
mvsjes2 Avatar answered Nov 20 '22 12:11

mvsjes2


Observer event type like this:

public void onEvent(int event) {
      if ((FileObserver.CREATE & event)!=0) {
        // do what ever you want.
      } else if ((FileObserver.MODIFY & event)!=0) {
        // do what ever you want.           
      } ...... etc
}
like image 5
user736435 Avatar answered Nov 20 '22 12:11

user736435


If anyone else comes here from Google, be aware of this from the documentation:

startWatching()

Start watching for events. The monitored file or directory must exist at this time, or else no events will be reported (even if it appears later). If monitoring is already started, this call has no effect.

like image 1
Jon McClung Avatar answered Nov 20 '22 13:11

Jon McClung