Work States and observing work
Work States
As your work goes through its lifetime, it goes through various State
s. 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 beENQUEUED
. - When a worker is actively being executed, it is in the
RUNNING
State
. - A worker that has returned
Result.success()
is considered to beSUCCEEDED
. This is a terminalState
; onlyOneTimeWorkRequest
s may enter thisState
. - Conversely, a worker that returned
Result.failure()
is considered to beFAILED
. This is also a terminalState
; onlyOneTimeWorkRequest
s may enter thisState
. All dependent work will also be marked asFAILED
and will not run. - When you explicitly cancel a
WorkRequest
that hasn't already terminated, it enters theCANCELLED
State
. All dependent work will also be marked asCANCELLED
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:
- For a specific
WorkRequest
, you can retrieve itsWorkInfo
by theWorkRequest
id
usingWorkManager.getWorkInfoById(UUID)
orWorkManager.getWorkInfoByIdLiveData(UUID)
. - For a given tag, you can retrieve
WorkInfo
objects for all matchingWorkRequest
s usingWorkManager.getWorkInfosByTag(String)
orWorkManager.getWorkInfosByTagLiveData(String)
. - For a unique work name, you can retrieve
WorkInfo
objects for all matchingWorkRequest
s usingWorkManager.getWorkInfosForUniqueWork(String)
orWorkManager.getWorkInfosForUniqueWorkLiveData(String)
获取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!")
}
}
});