Well, I seem to have the opposite problem of most FileObserver posts! Instead of onEvent never being called, mine is being called about 50 times . . . I must have set something up wrong but I'm running out of ideas. Can anyone see what I might have done wrong here?
FileObserverService:
import android.app.Service;
import android.content.Intent;
import android.os.FileObserver;
import android.os.IBinder;
import android.util.Log;
//public class FileObserverService {
public class FileObserverService extends Service{
private FileObserver mFileObserver;
int count = 0;
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i("Service", "OBS Service - On Start");
// if((intent.hasExtra(INTENT_EXTRA_FILEPATH))) // we store the path of directory inside the intent that starts the service
// mFileObserver = new FileObserver(intent.getStringExtra(INTENT_EXTRA_FILEPATH)) {
if((intent.hasExtra("filepath"))) // we store the path of directory inside the intent that starts the service
mFileObserver = new FileObserver(intent.getStringExtra("filepath")) {
@Override
public void onEvent(int event, String path) {
// If an event happens we can do stuff inside here
// for example we can send a broadcast message with the event-id
//Log.d("FILEOBSERVER_EVENT", "Event with id " + Integer.toHexString(event) + " happened"); // event identifies the occured Event in hex
switch(event){
case FileObserver.CREATE:
Log.d("OBS", "CREATE:" + path + count);
break;
case FileObserver.DELETE:
Log.d("OBS", "DELETE:" + path + count);
break;
case FileObserver.DELETE_SELF:
Log.d("OBS", "DELETE_SELF:" + path + count);
break;
case FileObserver.MODIFY:
Log.d("OBS", "MODIFY:" + path + count);
break;
case FileObserver.MOVED_FROM:
Log.d("OBS", "MOVED_FROM:" + path + count);
break;
case FileObserver.MOVED_TO:
Log.d("OBS", "MOVED_TO:" + path + count);
break;
case FileObserver.MOVE_SELF:
Log.d("OBS", "MOVE_SELF:" + path + count);
break;
default:
// just ignore
break;
}
count += 1;
}
};
mFileObserver.startWatching(); // The FileObserver starts watching
return Service.START_NOT_STICKY;
}
@Override
public void onCreate() {
super.onCreate();
}
@Override
public IBinder onBind(Intent intent) {
//TODO for communication return IBinder implementation
return null;
}
}
MainActivity:
public void ObsTapped(View view){
Log.i("OnClick", "ObsTapped");
//Insert code to observe change in file
Intent intent = new Intent(this, FileObserverService.class);
//intent.putExtra(INTENT_EXTRA_FILEPATH, "YOUR_FILEPATH");
intent.putExtra("filepath", "/storage/emulated/0/Pictures/filename.jpeg");
this.startService(intent);
//startService(new Intent(getBaseContext(), FileObserverService.class));
}
Below is a screenshot of the logs (the count goes up to null52 but it skipped null1 and null2):
Any idea what the issue could be?