我必须创建一个应用程序,在一天中的某些时间激活接近警报(这段时间可能长达几个小时)。 即使应用程序从未打开过,接近警报也必须自动启动。
我的问题是:在这种情况下我可以使用
WorkManager
吗?或者我应该回到foreground service
?
WorkManager 2.3.0-alpha02 添加了对长时间运行的内置支持 工人。在这种情况下,WorkManager 可以向操作系统提供信号 如果可能的话,在这项工作进行期间,应该保持该过程的活力 执行。这些工人可以运行超过10分钟。例子 此新功能的用例包括批量上传或下载(即 无法分块)、本地处理 ML 模型或任务 对于应用程序的用户来说很重要。
在底层,WorkManager 代表您管理和运行前台服务来执行 WorkRequest,同时还显示可配置的通知。
ListenableWorker 现在支持 setForegroundAsync() API,CoroutineWorker 支持暂停的 setForeground() API。这些 API 允许开发人员指定此 WorkRequest 是重要的(从用户角度来看)还是长时间运行。
从 2.3.0-alpha03 开始,WorkManager 还允许您创建 PendingIntent,它可用于取消工作线程,而无需使用 createCancelPendingIntent() API 注册新的 Android 组件。这种方法在与 setForegroundAsync() 或 setForeground() API 一起使用时特别有用,可用于添加取消 Worker 的通知操作。
资源链接:https://developer.android.com/topic/libraries/architecture/workmanager/advanced/long-running
不幸的是,你不能...上面的答案和android的文档非常具有误导性!仅当您的应用程序运行时启动时,才能执行前台工作。即使您在清单中设置了所有前台权限/服务,您也无法启动定期前台工作程序并期望它在应用程序每 6 小时关闭一次时在前台运行。只有当worker唤醒时应用程序打开时,它才会成功运行。 (是的,如果您的应用程序是系统应用程序、首选消息应用程序、设备刚刚启动,等等,则有例外 - 不是您的情况)。
应用程序关闭时工作人员的错误将是这样的:
2023-12-07 12:48:24.595 5362-5384 WM-Processor fr.esgi.firstfm.debug I Moving WorkSpec (eee6d859-109e-48c7-b957-95ab48d82ef8) to the foreground
2023-12-07 12:48:24.611 631-2173 ActivityManager system_server W Background started FGS: Disallowed [callingPackage: fr.esgi.firstfm.debug; callingUid: 10169; uidState: CEM ; intent: Intent { act=ACTION_START_FOREGROUND cmp=fr.esgi.firstfm.debug/androidx.work.impl.foreground.SystemForegroundService (has extras) }; code:DENIED; tempAllowListReason:<null>; targetSdkVersion:33; callerTargetSdkVersion:33; startForegroundCount:0; bindFromPackage:null]
2023-12-07 12:48:24.612 631-2173 ActivityManager system_server W startForegroundService() not allowed due to mAllowStartForeground false: service fr.esgi.firstfm.debug/androidx.work.impl.foreground.SystemForegroundService
但是当应用程序运行时,worker将会成功:
2023-12-07 18:58:30.247 24071-24111 WM-Processor fr.esgi.firstfm.debug I Moving WorkSpec (3cf8c83f-2971-4bc9-8b05-bdff019b0dca) to the foreground
2023-12-07 18:58:30.296 24071-24071 WM-SystemFgDispatcher fr.esgi.firstfm.debug I Started foreground service Intent { act=ACTION_START_FOREGROUND cmp=fr.esgi.firstfm.debug/androidx.work.impl.foreground.SystemForegroundService (has extras) }