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?
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");
}
}
}