你如何构建一个 Android 应用程序来启动一个 Dịch vụ
以使用一个 FileObserver
以便当观察到的目录被修改(即用户拍照)时执行一些其他代码.调试时,永远不会触发 onEvent 方法。
这是我的服务中的 onStart 事件。 Toast
触发“My Service Started...”
public final String TAG = "DEBUG";
public static FileObserver observer;
@Ghi đè
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
@Ghi đè
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);
//
}
};
}
但是在 Toast 之后,如果我拍照,onEvent 永远不会触发。这是由调试决定的。它永远不会达到那个断点,并且 Toast 永远不会触发。
浏览该目录时,新图像会保存在那里。
如何让 FileObserver
hiện hữu Dịch vụ
中工作?
请nhìn thấy这个帖子。我认为您在设置观察者后错过了 observer.startWatching()
调用。
observer = new FileObserver(pathToWatch) { // set up a file observer to watch this directory on sd card
@Ghi đè
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
Tôi là một lập trình viên xuất sắc, rất giỏi!