如何确保 WorkManager 取消我的 Worker? [英] How to make sure that WorkManager cancels my Worker?

查看:38
本文介绍了如何确保 WorkManager 取消我的 Worker?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

WorkManager 文档中提到取消 Worker 是尽力而为

It's mentioned in WorkManager documentation that cancelling a Worker is best-effort

WorkManager 尽最大努力取消任务,但这是固有的不确定性——任务可能已经在运行或完成时你试图取消它

WorkManager makes its best effort to cancel the task, but this is inherently uncertain--the task may already be running or finished when you attempt to cancel it

如果我有一个用例,强制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 开发者峰会上.

However, if the tasks it's already running, WorkManager cannot safely interrupt it. The best option is that you write your Worker class taking care of an external cancellation. This has been covered in the Working with WorkManager talk (around minute 15) recorded at the Android Developer Summit 2018.

要成为一个好公民,您可以使用以下方法汇集 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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆