5

I'm using a FileObserver to watch a folder in android. When a user modifies or creates a new file in this folder, the FileObserver should do some stuff with this file.

The thing is that with the use of the clause FileObserver.MODIFY, every time I create/modify a file in this watched folder, the FileObserver method onEvent() is called twice. This is a problem for me because it ruins everything I do afterwards (it's done twice).

This is my code:

mFileObserver = new FileObserver(directoryPath, FileObserver.MODIFY){
        public void onEvent(int event, String fileName){
            if (event == FileObserver.MODIFY){
                // some stuff to do
            }
        }
    }; 
Fernando
  • 751
  • 2
  • 13
  • 27
  • 2
    That's always going to be a risk when you asynchronously snoop on another process - try something like having a few seconds delay before you take action, and ignoring any subsequent events while you are already in the delay period. – Chris Stratton Nov 04 '14 at 23:27
  • Or, could you keep track of the previous event and fileName, and make use of that information somehow to prevent performing work twice on the same file? – Michael Krause Nov 04 '14 at 23:54

1 Answers1

1

FileObserver.CLOSE_WRITE is triggered when a file that was just written to is closed. You just need to check for that event only.

public void onEvent(int event, String fileName){
        if (event == FileObserver.CLOSE_WRITE){
            // some stuff to do
        }
    }
clementiano
  • 139
  • 2
  • 10