0

I want to implement a FileObserver to write a log whenever a certain file is changed. This should run anytime between boot and shutdown. After starting it no activity has to access it again.

I wrote a Service holding the instance of my FileObserver. But onEvent() only fires once and my service does not appear in adb shell service list at all.

Is this the wrong way to implement an ongoing background service?

public class MyService extends Service {

private static FileObserver fileObserver;

@Override
public void onCreate() {

File file = new File("path/to/file");

    if (file.canRead()) {

        fileObserver = new FileObserver(file.getAbsolutePath(), FileObserver.MODIFY) {
            @Override
            public void onEvent(int event, @Nullable String path) {
                Log.i("FileObserver", "File modified!");
            }
        };

        fileObserver.startWatching();

    } 
}
Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
phoeller
  • 58
  • 1
  • 10

1 Answers1

0

I think you need a foreground service which will keep running even you application is not in foreground. See the below example:

http://www.truiton.com/2014/10/android-foreground-service-example/

You can also try sticky service. This will make sure that your service is restarted when killed by Android. Check the below link. https://www.b4x.com/android/forum/threads/creating-a-sticky-service-long-running-background-tasks.27065/

KR_Android
  • 1,149
  • 9
  • 19