I'm creating an android app that runs a service via a broadcast receiver at startup. The service, in turn, runs a fileobserver class to monitor a directory. When creating a file in the monitored directory, i need the service to restart. Is it possibile to restart the service in the fileobserver class event?
Asked
Active
Viewed 44 times
0
-
Instead of restarting the service, couldn't you use the FileObserver to reset the state of your already running service when a file/directory change is detected? – Bradford2000 Jul 11 '18 at 21:38
-
Bradford2000 thanks for the reply. Could you give me an example? – user10067214 Jul 11 '18 at 21:42
1 Answers
0
You could do something like this and not have to restart your Service (just update the Service state as file change events are detected).
public class MyService extends Service {
private FileObserver observer;
@Override
public int onStartCommand(final Intent intent, final int flags, final int startId) {
init("path/to/watch");
return super.onStartCommand(intent, flags, startId);
}
@Nullable
@Override
public IBinder onBind(final Intent intent) {
return null;
}
private void init(final String pathToWatch) {
observer = new FileObserver(pathToWatch) {
@Override
public void onEvent(final int event, @Nullable final String path) {
onFileChangeEvent(path);
}
};
observer.startWatching();
}
private void onFileChangeEvent(final String path) {
if(condition) {
observer.stopWatching();
init("new/path/to/watch");
}
}
}

Bradford2000
- 723
- 3
- 14
-
Good. In my app, however, I need to dynamically change the path monitored by the fileobserver quite often or to terminate the old fileobserver instance and start another with the new path. For this reason I thought, at first, to finish the service and re-run it with the new path. What do you suggest? – user10067214 Jul 11 '18 at 22:39
-
For that, you can stop the current FileObserver and start a new one. I'll update my answer to illustrate. – Bradford2000 Jul 11 '18 at 22:56
-
1Many thanks Bradford2000 for your valuable contribution. I solved my problem based on your answer. – user10067214 Jul 12 '18 at 22:01