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();
}
}