觀察 worker 中繼進度
透過集合功能整理內容
你可以依據偏好儲存及分類內容。
WorkManager 內建支援設定及觀察工作站的中階進度。如果工作站在應用程式於前景運作時執行,該資訊也可透過會回傳 WorkInfo
的 LiveData
API 向使用者顯示這項資訊。
ListenableWorker
現在支援 setProgressAsync()
API,可使其保留中階進度。這些 API 可讓開發人員設定使用者介面可察看的中階進度。系統會以 Data
類型表示進度,其為屬性的可序列化容器 (類似於 input
和 output
,並且受到相同的限制)。
只有在 ListenableWorker
執行期間,才能查看及更新進度資訊。嘗試在 ListenableWorker
上設定進度,且執行作業完成後就會被忽略。
您也可以使用 getWorkInfoBy…()
或 getWorkInfoBy…LiveData()
方式察看進度資訊。這些方法會回傳 WorkInfo
的執行個體,而新的 getProgress()
方法會回傳 Data
。
更新進度
針對使用 ListenableWorker
或 Worker
的 Java 開發人員,setProgressAsync()
API 會回傳 ListenableFuture<Void>
;更新進度並非同步,因為更新程序需要將進度資訊儲存在資料庫中。在 Kotlin 中,您可以使用 CoroutineWorker
物件的 setProgress()
擴充功能函式來更新進度資訊。
這個範例顯示 ProgressWorker
。Worker
會在開始時將進度設為 0,完成時則將進度值更新為 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();
}
}
查看進度
如要查看進度資訊,請使用 getWorkInfoById
方法,並取得 WorkInfo
的參照。
以下是使用 getWorkInfoByIdFlow
(適用於 Kotlin) 和 getWorkInfoByIdLiveData
(適用於 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
}
}
});
如要進一步瞭解如何查看 Worker
物件,請參閱「作業狀態和查看作業」。如要瞭解如何在工作意外終止時取得 stopReason,請參閱「觀察停止原因狀態」。
這個頁面中的內容和程式碼範例均受《內容授權》中的授權所規範。Java 與 OpenJDK 是 Oracle 和/或其關係企業的商標或註冊商標。
上次更新時間:2025-08-22 (世界標準時間)。
[null,null,["上次更新時間:2025-08-22 (世界標準時間)。"],[],[],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)."]]