How to make sure that WorkManager cancels my Worker?

混江龙づ霸主 提交于 2019-12-10 20:51:17

问题


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

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

What if i have a use case that it's mandatory that the Worker gets cancelled upon calling one of the cancelling methods?


回答1:


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.

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.

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.



来源:https://stackoverflow.com/questions/53924702/how-to-make-sure-that-workmanager-cancels-my-worker

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!