保持文件观察者在后台运行,即使应用程序已关闭。

huangapple go评论73阅读模式
英文:

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,用于通知用户您的应用正在后台运行。据我所知,当任何文件夹内容发生更改时,没有任何监听器会触发...

您还可以使用AlarmManagerWorkManager定期触发您的代码,但仍然可能会有一些延迟,可能不会在精确的时间触发,和/或可能会耗电(系统会惩罚您的应用,标记为“耗电应用”,并建议用户强制停止/卸载,您还可能会在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)

huangapple
  • 本文由 发表于 2020年10月23日 14:38:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/64495071.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定