WorkManager系列(四) Work States and observing work

博客介绍了工作在其生命周期中的各种状态,如BLOCKED、ENQUEUED等六种状态,还说明了如何观察工作状态。WorkManager允许在工作入队后检查其状态,可通过三种方式获取状态信息,部分方法变体还能通过注册监听器观察状态变化。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Work States and observing work

Work States

As your work goes through its lifetime, it goes through various States. Later in this document, we will talk about how to observe the changes. But first, you should learn about each of them:

  • Work is in the BLOCKED State if it has prerequisite work that hasn't finished yet.
  • Work that is eligible to run as soon as its Constraints and timing are met is considered to be ENQUEUED.
  • When a worker is actively being executed, it is in the RUNNING State.
  • A worker that has returned Result.success() is considered to be SUCCEEDED. This is a terminal State; only OneTimeWorkRequests may enter this State.
  • Conversely, a worker that returned Result.failure() is considered to be FAILED. This is also a terminal State; only OneTimeWorkRequests may enter this State. All dependent work will also be marked as FAILED and will not run.
  • When you explicitly cancel a WorkRequest that hasn't already terminated, it enters the CANCELLED State. All dependent work will also be marked as CANCELLED and will not run.

翻译:共有

BLOCKED

ENQUEUED

RUNNING

SUCCEEDED

FAILED

CANCELED 

六种状态

Observing your work

After you enqueue your work, WorkManager allows you to check on its status. This information is available in a WorkInfo object, which includes the id of the work, its tags, its current State, and any output data.

You can obtain WorkInfo in one of three ways:

获取workInfo 的三种方法

 

The LiveData variants of each of the methods allow you to observe changes to the WorkInfo by registering a listener. For example, if you wanted to display a message to the user when some work finishes successfully, you could set it up as follows:

WorkManager.getInstance().getWorkInfoByIdLiveData(uploadWorkRequest.getId())
        .observe(lifecycleOwner, new Observer<WorkInfo>() {
            @Override
            public void onChanged(@Nullable WorkInfo workInfo) {
              if (workInfo != null && workInfo.state == WorkInfo.State.SUCCEEDED) {
                  displayMessage("Work finished!")
              }
            }
        });

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值