gpt4 book ai didi

java - 如何从 Android 服务实现 FileObserver

转载 作者:IT老高 更新时间:2023-10-28 21:13:59 24 4
gpt4 key购买 nike

你如何构建一个 Android 应用程序来启动一个 Service 以使用一个 FileObserver 以便当观察到的目录被修改(即用户拍照)时执行一些其他代码.调试时,永远不会触发 onEvent 方法。

这是我的服务中的 onStart 事件。 Toast 触发“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);
//}
}
};
}

但是在 Toast 之后,如果我拍照,onEvent 永远不会触发。这是由调试决定的。它永远不会达到那个断点,并且 Toast 永远不会触发。

浏览该目录时,新图像会保存在那里。

如何让 FileObserverService 中工作?

最佳答案

see这个帖子。我认为您在设置观察者后错过了 observer.startWatching() 调用。

 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

关于java - 如何从 Android 服务实现 FileObserver,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7265906/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com