2

I have an Android app and I want to monitor a folder. I made a service(I want to monitor the folder non-stop, even if the user kill the app) and I put the folder's path in the extras of the Intent. In the service I have a FileObserver that should monitor my folder and trigger an event whenever a file is created inside the folder. The problem is that event is never triggered. Am I doing something wrong? Thanks!

@Override
public int onStartCommand(Intent intent, int flags, int startId){

    String mainFolder = intent.getStringExtra("mainFolder");

    Toast.makeText(getApplicationContext(), "Service start! Main folder is: " + mainFolder, Toast.LENGTH_LONG).show();

    FileObserver observer = new FileObserver(mainFolder) {
            @Override
            public void onEvent(int event, String path) {
                if (path == null) {
                    return;
                }
                if (FileObserver.CREATE == event) {
                    Toast.makeText(getApplicationContext(), "This file was creted: " + path, Toast.LENGTH_LONG).show();

                }
            }
        };

    observer.startWatching();

    return START_REDELIVER_INTENT;
}
Alex Hash
  • 21
  • 1

1 Answers1

0

Quoting the documentation for FileObserver:

Warning: If a FileObserver is garbage collected, it will stop sending events. To ensure you keep receiving events, you must keep a reference to the FileObserver instance from some other live object.

Your FileObserver instance is eligible for garbage collection as soon as onStartCommand() returns, as you are not holding it in a field, but in a local variable.

Also, bear in mind that services do not run forever.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
  • Thank you for your answer!I understand that a service not runs forever, but that "return START_REDELIVER_INTENT;" statement should reopen the service. – Alex Hash Jul 12 '17 at 13:58
  • @AlexHash: Yes, but since your service is not a foreground service, on Android 8.0+, it will run for a minute or so, then be stopped. – CommonsWare Jul 12 '17 at 14:27