Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you implement a FileObserver from an Android Service

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?

like image 685
shanabus Avatar asked Sep 01 '11 03:09

shanabus


2 Answers

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  
like image 70
Jack Avatar answered Oct 05 '22 04:10

Jack


Add .show() after toast, i.e.

Toast.makeText(getBaseContext(), file + " was saved!", toast.LENGTH_LONG).show();                   
like image 28
Sujith Manjavana Avatar answered Oct 05 '22 04:10

Sujith Manjavana