Observar o andamento intermediário do worker
Mantenha tudo organizado com as coleções
Salve e categorize o conteúdo com base nas suas preferências.
O WorkManager tem suporte integrado para definir e observar o andamento intermediário de workers. Se o worker estava em execução enquanto o app estava
em primeiro plano, essas informações também podem ser mostradas para o usuário usando APIs
que retornam o LiveData
de WorkInfo
.
O ListenableWorker
agora oferece suporte à API
setProgressAsync()
,
que possibilita que ele se mantenha no andamento intermediário. Essas APIs permitem
que os desenvolvedores definam um andamento intermediário que pode ser observado pela IU.
O andamento é representado pelo tipo Data
,
que é um contêiner serializável de propriedades, semelhante a input
e
output
e
sujeito às mesmas restrições.
As informações de andamento só podem ser observadas e atualizadas enquanto o
ListenableWorker
está em execução. As tentativas de definir o andamento em um ListenableWorker
após o término da execução serão ignoradas.
Também é possível observar informações
de progresso usando um dos métodos
getWorkInfoBy…()
ou
getWorkInfoBy…LiveData()
. Esses métodos retornam instâncias de
WorkInfo
, que tem um novo método
getProgress()
que
retorna Data
.
Atualizar progresso
Para desenvolvedores Java que usam ListenableWorker
ou Worker
, a API
setProgressAsync()
retorna um ListenableFuture<Void>
. A atualização do andamento é assíncrona,
já que o processo de atualização envolve o armazenamento de informações em um banco de dados.
Em Kotlin, você pode usar a função de extensão setProgress()
do objeto CoroutineWorker
para atualizar informações de andamento.
Este exemplo mostra um ProgressWorker
. O Worker
configura o andamento como
0 quando é iniciado e, após a conclusão, atualiza o valor do andamento para 100.
Kotlin
import android.content.Context
import androidx.work.CoroutineWorker
import androidx.work.Data
import androidx.work.WorkerParameters
import kotlinx.coroutines.delay
class ProgressWorker(context: Context, parameters: WorkerParameters) :
CoroutineWorker(context, parameters) {
companion object {
const val Progress = "Progress"
private const val delayDuration = 1L
}
override suspend fun doWork(): Result {
val firstUpdate = workDataOf(Progress to 0)
val lastUpdate = workDataOf(Progress to 100)
setProgress(firstUpdate)
delay(delayDuration)
setProgress(lastUpdate)
return Result.success()
}
}
Java
import android.content.Context;
import androidx.annotation.NonNull;
import androidx.work.Data;
import androidx.work.Worker;
import androidx.work.WorkerParameters;
public class ProgressWorker extends Worker {
private static final String PROGRESS = "PROGRESS";
private static final long DELAY = 1000L;
public ProgressWorker(
@NonNull Context context,
@NonNull WorkerParameters parameters) {
super(context, parameters);
// Set initial progress to 0
setProgressAsync(new Data.Builder().putInt(PROGRESS, 0).build());
}
@NonNull
@Override
public Result doWork() {
try {
// Doing work.
Thread.sleep(DELAY);
} catch (InterruptedException exception) {
// ... handle exception
}
// Set progress to 100 after you are done doing your work.
setProgressAsync(new Data.Builder().putInt(PROGRESS, 100).build());
return Result.success();
}
}
Observar o andamento
Para observar informações de progresso, use os métodos getWorkInfoById
e receba uma referência a
WorkInfo
.
Confira um exemplo que usa getWorkInfoByIdFlow
para Kotlin e getWorkInfoByIdLiveData
para Java.
Kotlin
WorkManager.getInstance(applicationContext)
// requestId is the WorkRequest id
.getWorkInfoByIdFlow(requestId)
.collect { workInfo: WorkInfo? ->
if (workInfo != null) {
val progress = workInfo.progress
val value = progress.getInt("Progress", 0)
// Do something with progress information
}
}
Java
WorkManager.getInstance(getApplicationContext())
// requestId is the WorkRequest id
.getWorkInfoByIdLiveData(requestId)
.observe(lifecycleOwner, new Observer<WorkInfo>() {
@Override
public void onChanged(@Nullable WorkInfo workInfo) {
if (workInfo != null) {
Data progress = workInfo.getProgress();
int value = progress.getInt(PROGRESS, 0)
// Do something with progress
}
}
});
Para ver mais documentação sobre como observar objetos Worker
, leia
Estados de trabalho e como observar trabalhos.
Para saber como receber o stopReason
quando o trabalho é encerrado inesperadamente, consulte Observar o estado do motivo da interrupção.
O conteúdo e os exemplos de código nesta página estão sujeitos às licenças descritas na Licença de conteúdo. Java e OpenJDK são marcas registradas da Oracle e/ou suas afiliadas.
Última atualização 2025-08-22 UTC.
[[["Fácil de entender","easyToUnderstand","thumb-up"],["Meu problema foi resolvido","solvedMyProblem","thumb-up"],["Outro","otherUp","thumb-up"]],[["Não contém as informações de que eu preciso","missingTheInformationINeed","thumb-down"],["Muito complicado / etapas demais","tooComplicatedTooManySteps","thumb-down"],["Desatualizado","outOfDate","thumb-down"],["Problema na tradução","translationIssue","thumb-down"],["Problema com as amostras / o código","samplesCodeIssue","thumb-down"],["Outro","otherDown","thumb-down"]],["Última atualização 2025-08-22 UTC."],[],[],null,["# Observe intermediate worker progress\n\nWorkManager has built-in support for setting and observing intermediate\nprogress for workers. If the worker was running while the app was in the\nforeground, this information can also be shown to the user using APIs which\nreturn the [`LiveData`](/reference/androidx/lifecycle/LiveData) of\n[`WorkInfo`](/reference/androidx/work/WorkInfo).\n\n[`ListenableWorker`](/reference/androidx/work/ListenableWorker) now supports the\n[`setProgressAsync()`](/reference/androidx/work/ListenableWorker#setProgressAsync(androidx.work.Data))\nAPI, which allows it to persist intermediate progress. These APIs allow\ndevelopers to set intermediate progress that can be observed by the UI.\nProgress is represented by the [`Data`](/reference/androidx/work/Data) type,\nwhich is a serializable container of properties (similar to [`input` and\n`output`](/topic/libraries/architecture/workmanager/advanced#params),\nand subject to the same restrictions).\n\nProgress information can only be observed and updated while the\n`ListenableWorker` is running. Attempts to set progress on a `ListenableWorker`\nafter it has completed its execution are ignored.\n\nYou can also observe progress\ninformation by using the one of the [`getWorkInfoBy...()` or\n`getWorkInfoBy...LiveData()`](/reference/androidx/work/WorkManager#getWorkInfoById(java.util.UUID))\nmethods. These methods return instances of\n[`WorkInfo`](/reference/androidx/work/WorkInfo), which has a new\n[`getProgress()`](/reference/androidx/work/WorkInfo#getProgress()) method\nthat returns `Data`.\n\nUpdate Progress\n---------------\n\nFor Java developers using a [`ListenableWorker`](/reference/androidx/work/ListenableWorker)\nor a [`Worker`](/reference/androidx/work/Worker), the\n[`setProgressAsync()`](/reference/androidx/work/ListenableWorker#setProgressAsync(androidx.work.Data))\nAPI returns a `ListenableFuture\u003cVoid\u003e`; updating progress is asynchronous,\ngiven that the update process involves storing progress information in a database.\nIn Kotlin, you can use the [`CoroutineWorker`](/reference/kotlin/androidx/work/CoroutineWorker)\nobject's [`setProgress()`](/reference/kotlin/androidx/work/CoroutineWorker#setprogress)\nextension function to update progress information.\n\nThis example shows a `ProgressWorker`. The `Worker` sets its progress to\n0 when it starts, and upon completion updates the progress value to 100. \n\n### Kotlin\n\n import android.content.Context\n import androidx.work.CoroutineWorker\n import androidx.work.Data\n import androidx.work.WorkerParameters\n import kotlinx.coroutines.delay\n\n class ProgressWorker(context: Context, parameters: WorkerParameters) :\n CoroutineWorker(context, parameters) {\n\n companion object {\n const val Progress = \"Progress\"\n private const val delayDuration = 1L\n }\n\n override suspend fun doWork(): Result {\n val firstUpdate = workDataOf(Progress to 0)\n val lastUpdate = workDataOf(Progress to 100)\n setProgress(firstUpdate)\n delay(delayDuration)\n setProgress(lastUpdate)\n return Result.success()\n }\n }\n\n### Java\n\n import android.content.Context;\n import androidx.annotation.NonNull;\n import androidx.work.Data;\n import androidx.work.Worker;\n import androidx.work.WorkerParameters;\n\n public class ProgressWorker extends Worker {\n\n private static final String PROGRESS = \"PROGRESS\";\n private static final long DELAY = 1000L;\n\n public ProgressWorker(\n @NonNull Context context,\n @NonNull WorkerParameters parameters) {\n super(context, parameters);\n // Set initial progress to 0\n setProgressAsync(new Data.Builder().putInt(PROGRESS, 0).build());\n }\n\n @NonNull\n @Override\n public Result doWork() {\n try {\n // Doing work.\n Thread.sleep(DELAY);\n } catch (InterruptedException exception) {\n // ... handle exception\n }\n // Set progress to 100 after you are done doing your work.\n setProgressAsync(new Data.Builder().putInt(PROGRESS, 100).build());\n return Result.success();\n }\n }\n\nObserving Progress\n------------------\n\nTo observe progress information, use the [`getWorkInfoById`](/reference/androidx/work/WorkManager#getWorkInfoById(java.util.UUID)) methods, and get a reference to\n[`WorkInfo`](/reference/androidx/work/WorkInfo).\n\nHere is an example which uses `getWorkInfoByIdFlow` for Kotlin and\n`getWorkInfoByIdLiveData` for Java. \n\n### Kotlin\n\n WorkManager.getInstance(applicationContext)\n // requestId is the WorkRequest id\n .getWorkInfoByIdFlow(requestId)\n .collect { workInfo: WorkInfo? -\u003e\n if (workInfo != null) {\n val progress = workInfo.progress\n val value = progress.getInt(\"Progress\", 0)\n // Do something with progress information\n }\n }\n\n### Java\n\n WorkManager.getInstance(getApplicationContext())\n // requestId is the WorkRequest id\n .getWorkInfoByIdLiveData(requestId)\n .observe(lifecycleOwner, new Observer\u003cWorkInfo\u003e() {\n @Override\n public void onChanged(@Nullable WorkInfo workInfo) {\n if (workInfo != null) {\n Data progress = workInfo.getProgress();\n int value = progress.getInt(PROGRESS, 0)\n // Do something with progress\n }\n }\n });\n\nFor more documentation on observing `Worker` objects, read\n[Work States and observing work](/topic/libraries/architecture/workmanager/how-to/states-and-observation).\nTo learn how to get the [stopReason](/reference/androidx/work/WorkInfo#getStopReason())\nwhen work terminates unexpectedly, reference [Observe stop reason state](/develop/background-work/background-tasks/persistent/how-to/manage-work#stop-reason)."]]