我希望实现一个FileObserver,以便在更改某个文件时写入日志。这应该在启动和关闭之间的任何时候运行。启动后,没有任何活动必须再次访问它。
我编写了一个保存我的Service实例的FileObserver。但是onEvent()只触发一次,而我的服务根本没有出现在adb shell service list中。
这是不是实现正在进行的后台服务的错误方式?
public class MyService extends Service {
private static FileObserver fileObserver;
@Override
public void onCreate() {
File file = new File("path/to/file");
if (file.canRead()) {
fileObserver = new FileObserver(file.getAbsolutePath(), FileObserver.MODIFY) {
@Override
public void onEvent(int event, @Nullable String path) {
Log.i("FileObserver", "File modified!");
}
};
fileObserver.startWatching();
}
}发布于 2018-04-18 14:44:05
我认为您需要一个前台服务,即使您的应用程序不在前台,它也会继续运行。见下面的示例:
http://www.truiton.com/2014/10/android-foreground-service-example/
您也可以尝试粘性服务。这将确保您的服务在被Android杀死时重新启动。检查下面的链接。https://www.b4x.com/android/forum/threads/creating-a-sticky-service-long-running-background-tasks.27065/
https://stackoverflow.com/questions/49902491
复制相似问题