How do you structure an Android app to start a Service
to use a FileObserver
so that when the observed directory is modified (ie user takes picture) some other code executes. When debugging, the onEvent method is never triggered.
Here is the onStart event I have in my Service. The Toast
fires for "My Service Started..."
public final String TAG = "DEBUG"; public static FileObserver observer; @Override public void onStart(Intent intent, int startid) { Log.d(TAG, "onStart"); final String pathToWatch = android.os.Environment.getExternalStorageDirectory().toString() + "/DCIM/Camera/"; Toast.makeText(this, "My Service Started and trying to watch " + pathToWatch, Toast.LENGTH_LONG).show(); observer = new FileObserver(pathToWatch) { // set up a file observer to watch this directory on sd card @Override public void onEvent(int event, String file) { //if(event == FileObserver.CREATE && !file.equals(".probe")){ // check if its a "create" and not equal to .probe because thats created every time camera is launched Log.d(TAG, "File created [" + pathToWatch + file + "]"); Toast.makeText(getBaseContext(), file + " was saved!", Toast.LENGTH_LONG); //} } }; }
But after that Toast, if I take a picture the onEvent never fires. This is determined by debugging. It never hits that breakpoint and the Toast never fires.
When that directory is browsed, the new image is saved there.
How do you get a FileObserver
working in a Service
?
Please see this post. I think you are missing the observer.startWatching()
call after you setup your observer.
observer = new FileObserver(pathToWatch) { // set up a file observer to watch this directory on sd card @Override public void onEvent(int event, String file) { //if(event == FileObserver.CREATE && !file.equals(".probe")){ // check if its a "create" and not equal to .probe because thats created every time camera is launched Log.d(TAG, "File created [" + pathToWatch + file + "]"); Toast.makeText(getBaseContext(), file + " was saved!", Toast.LENGTH_LONG).show(); //} } }; observer.startWatching(); //START OBSERVING
Add .show()
after toast
, i.e.
Toast.makeText(getBaseContext(), file + " was saved!", toast.LENGTH_LONG).show();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With