Tuesday, May 14, 2013

[android help] 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?



.

stackoverflow.comm

No comments:

Post a Comment

Google Voice on T-Mobile? [General]

Google Voice on T-Mobile? So I recently switched from a GNex on Verizon to a Moto X DE on T-Mobile. I had always used Google Voice for my v...