CoroutineWorker 中的线程处理
使用集合让一切井井有条
根据您的偏好保存内容并对其进行分类。
对于 Kotlin 用户,WorkManager 为协程提供了一流的支持。如要开始使用,请将 work-runtime-ktx
包含到您的 gradle 文件中。不要扩展 Worker
,而应扩展 CoroutineWorker
,后者包含 doWork()
的挂起版本。例如,如果要构建简单的 CoroutineWorker
来执行某些网络操作,您需要执行以下操作:
class CoroutineDownloadWorker(
context: Context,
params: WorkerParameters
) : CoroutineWorker(context, params) {
override suspend fun doWork(): Result {
val data = downloadSynchronously("https://www.google.com")
saveData(data)
return Result.success()
}
}
请注意,CoroutineWorker.doWork()
是一个“挂起”函数。此代码不同于 Worker
,不会在 Configuration
中指定的 Executor
中运行,而是默认为 Dispatchers.Default
。您可以提供自己的 CoroutineContext
来自定义这个行为。在上面的示例中,您可能希望在 Dispatchers.IO
上完成此操作,如下所示:
class CoroutineDownloadWorker(
context: Context,
params: WorkerParameters
) : CoroutineWorker(context, params) {
override suspend fun doWork(): Result {
withContext(Dispatchers.IO) {
val data = downloadSynchronously("https://www.google.com")
saveData(data)
return Result.success()
}
}
}
CoroutineWorker
通过取消协程并传播取消信号来自动处理停工情况。您无需执行任何特殊操作来处理停工情况。
在其他进程中运行 CoroutineWorker
您还可以使用 RemoteCoroutineWorker
(ListenableWorker
的实现)将工作器绑定到特定进程。
RemoteCoroutineWorker
会使用您在构建工作请求时于输入数据中提供的两个额外参数绑定到特定进程:ARGUMENT_CLASS_NAME
和 ARGUMENT_PACKAGE_NAME
。
以下示例演示了如何构建绑定到特定进程的工作请求:
Kotlin
val PACKAGE_NAME = "com.example.background.multiprocess"
val serviceName = RemoteWorkerService::class.java.name
val componentName = ComponentName(PACKAGE_NAME, serviceName)
val data: Data = Data.Builder()
.putString(ARGUMENT_PACKAGE_NAME, componentName.packageName)
.putString(ARGUMENT_CLASS_NAME, componentName.className)
.build()
return OneTimeWorkRequest.Builder(ExampleRemoteCoroutineWorker::class.java)
.setInputData(data)
.build()
Java
String PACKAGE_NAME = "com.example.background.multiprocess";
String serviceName = RemoteWorkerService.class.getName();
ComponentName componentName = new ComponentName(PACKAGE_NAME, serviceName);
Data data = new Data.Builder()
.putString(ARGUMENT_PACKAGE_NAME, componentName.getPackageName())
.putString(ARGUMENT_CLASS_NAME, componentName.getClassName())
.build();
return new OneTimeWorkRequest.Builder(ExampleRemoteCoroutineWorker.class)
.setInputData(data)
.build();
对于每个 RemoteWorkerService
,您还需要在 AndroidManifest.xml
文件中添加服务定义:
<manifest ... >
<service
android:name="androidx.work.multiprocess.RemoteWorkerService"
android:exported="false"
android:process=":worker1" />
<service
android:name=".RemoteWorkerService2"
android:exported="false"
android:process=":worker2" />
...
</manifest>
本页面上的内容和代码示例受内容许可部分所述许可的限制。Java 和 OpenJDK 是 Oracle 和/或其关联公司的注册商标。
最后更新时间 (UTC):2025-07-27。
[[["易于理解","easyToUnderstand","thumb-up"],["解决了我的问题","solvedMyProblem","thumb-up"],["其他","otherUp","thumb-up"]],[["没有我需要的信息","missingTheInformationINeed","thumb-down"],["太复杂/步骤太多","tooComplicatedTooManySteps","thumb-down"],["内容需要更新","outOfDate","thumb-down"],["翻译问题","translationIssue","thumb-down"],["示例/代码问题","samplesCodeIssue","thumb-down"],["其他","otherDown","thumb-down"]],["最后更新时间 (UTC):2025-07-27。"],[],[],null,["# Threading in CoroutineWorker\n\nFor Kotlin users, WorkManager provides first-class support for [coroutines](https://kotlinlang.org/docs/reference/coroutines-overview.html). To get\nstarted, include [`work-runtime-ktx` in your gradle file](/jetpack/androidx/releases/work#declaring_dependencies). Instead of extending [`Worker`](/reference/androidx/work/Worker), you should extend [`CoroutineWorker`](/reference/kotlin/androidx/work/CoroutineWorker), which has a suspending\nversion of `doWork()`. For example, if you wanted to build a simple `CoroutineWorker`\nto perform some network operations, you would do the following: \n\n class CoroutineDownloadWorker(\n context: Context,\n params: WorkerParameters\n ) : CoroutineWorker(context, params) {\n\n override suspend fun doWork(): Result {\n val data = downloadSynchronously(\"https://www.google.com\")\n saveData(data)\n return Result.success()\n }\n }\n\nNote that [`CoroutineWorker.doWork()`](/reference/kotlin/androidx/work/CoroutineWorker#doWork()) is a *suspending*\nfunction. Unlike `Worker`, this code does *not* run on the `Executor` specified\nin your [`Configuration`](/reference/androidx/work/Configuration). Instead, it\ndefaults to `Dispatchers.Default`. You can customize this by providing your own `CoroutineContext`. In the above example, you would probably want to do this work on `Dispatchers.IO`, as follows: \n\n class CoroutineDownloadWorker(\n context: Context,\n params: WorkerParameters\n ) : CoroutineWorker(context, params) {\n\n override suspend fun doWork(): Result {\n withContext(Dispatchers.IO) {\n val data = downloadSynchronously(\"https://www.google.com\")\n saveData(data)\n return Result.success()\n }\n }\n }\n\n`CoroutineWorker` handles stoppages automatically by cancelling the coroutine\nand propagating the cancellation signals. You don't need to do anything special\nto handle [work stoppages](/topic/libraries/architecture/workmanager/how-to/managing-work#cancelling).\n\nRunning a CoroutineWorker in a different process\n------------------------------------------------\n\nYou can also bind a worker to a specific process by using\n[`RemoteCoroutineWorker`](/reference/kotlin/androidx/work/multiprocess/RemoteCoroutineWorker),\nan implementation of `ListenableWorker`.\n\n`RemoteCoroutineWorker` binds to a specific process with two extra arguments\nthat you provide as part of the input data when building the work request:\n`ARGUMENT_CLASS_NAME` and `ARGUMENT_PACKAGE_NAME`.\n\nThe following example demonstrates building a work request that is bound to a\nspecific process: \n\n### Kotlin\n\n```kotlin\nval PACKAGE_NAME = \"com.example.background.multiprocess\"\n\nval serviceName = RemoteWorkerService::class.java.name\nval componentName = ComponentName(PACKAGE_NAME, serviceName)\n\nval data: Data = Data.Builder()\n .putString(ARGUMENT_PACKAGE_NAME, componentName.packageName)\n .putString(ARGUMENT_CLASS_NAME, componentName.className)\n .build()\n\nreturn OneTimeWorkRequest.Builder(ExampleRemoteCoroutineWorker::class.java)\n .setInputData(data)\n .build()\n```\n\n### Java\n\n```java\nString PACKAGE_NAME = \"com.example.background.multiprocess\";\n\nString serviceName = RemoteWorkerService.class.getName();\nComponentName componentName = new ComponentName(PACKAGE_NAME, serviceName);\n\nData data = new Data.Builder()\n .putString(ARGUMENT_PACKAGE_NAME, componentName.getPackageName())\n .putString(ARGUMENT_CLASS_NAME, componentName.getClassName())\n .build();\n\nreturn new OneTimeWorkRequest.Builder(ExampleRemoteCoroutineWorker.class)\n .setInputData(data)\n .build();\n```\n\nFor each `RemoteWorkerService`, you also need to add a service definition in\nyour `AndroidManifest.xml` file: \n\n```xml\n\u003cmanifest ... \u003e\n \u003cservice\n android:name=\"androidx.work.multiprocess.RemoteWorkerService\"\n android:exported=\"false\"\n android:process=\":worker1\" /\u003e\n\n \u003cservice\n android:name=\".RemoteWorkerService2\"\n android:exported=\"false\"\n android:process=\":worker2\" /\u003e\n ...\n\u003c/manifest\u003e\n```"]]