英文:
Keep file observer running in background even if the app is closed
问题
我已经创建了一个文件观察器对象,它正常运行。但是我的要求是,即使用户手动关闭了应用,也要保持文件观察器的活动状态。我本可以使用服务来保持它的运行,但是在安卓 O 之后,这种方式不再被允许。现在你可能会建议使用作业调度器,但是我希望文件观察器能在文件/文件夹更新时立即触发事件。有什么办法可以做到这一点吗?提前谢谢你。
英文:
I have created a file observer object and it is working fine. But my requirement is to keep the file observer alive even if the app is closed manually by the user. I could have used service to keep it running but after android O that thing is not allowed anymore. Now you may say use job scheduler but I want fileObserver to fire the event as soon as the file/folder is updated.
is there any way to do so?
thank you in advance
答案1
得分: 1
目前您只有一种选择来实现这个功能 - 使用前台服务(ForegroundService)。它的工作方式类似于普通的Service,但是必须保持粘性Notification,用于通知用户您的应用正在后台运行。据我所知,当任何文件夹内容发生更改时,没有任何监听器会触发...
您还可以使用AlarmManager或WorkManager定期触发您的代码,但仍然可能会有一些延迟,可能不会在精确的时间触发,和/或可能会耗电(系统会惩罚您的应用,标记为“耗电应用”,并建议用户强制停止/卸载,您还可能会在GP商店中被禁止)。
英文:
currently you have only one option for doing this - use ForegroundService. its working just like usual Service, but it have to keep sticky Notification, which informs user that your app is working in background. as far as I know there is no listener firing when any folder content change...
you can also fire your code from time to time with AlarmManager or WorkManager, but still it may have some delay, may not fire in exact time and/or may drain battery (system will punish your app, flag as "battery drainer" and suggest user to force stop/uninstall, you can also get banned in GP Store)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论