问题描述
WorkManager 文档中提到取消 Worker 是尽力而为
It's mentioned in WorkManager documentation that cancelling a Worker is best-effort
WorkManager 尽最大努力取消任务,但这是固有的不确定性——任务可能已经在运行或完成时你试图取消它
如果我有一个用例,强制Worker
在调用取消方法之一时被取消怎么办?
What if i have a use case that it's mandatory that the Worker
gets cancelled upon calling one of the cancelling methods?
推荐答案
正如您所写,WorkManager 只能尽力取消工作.特别是,如果一个任务计划运行,而您取消它,WorkManager 会将其从计划中删除.
As you wrote WorkManager can only try with a best-effort to cancel a work. In particular, if a task is scheduled to run, and you cancel it, WorkManager will remove it from the schedule.
但是,如果任务已经在运行,WorkManager 不能安全地中断它.最好的选择是您编写 Worker 类来处理外部取消.使用 WorkManager 谈话(大约 15 分钟) 中对此进行了介绍a> 记录在 2018 年 Android 开发者峰会上.
要成为一个好公民,您可以使用以下方法汇集 WorkManager:ListenableWorker.isStopped()
.您可以将此与 onStopped
当您或操作系统请求停止任务时用于清理代码的回调.
To be a good citizen you can pool WorkManager using the method: ListenableWorker.isStopped()
. You can combine this with the onStopped
callback to cleanup your code when you or the OS request to stop the task.
这篇关于如何确保 WorkManager 取消我的 Worker?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!