การจัดชุดข้อความใน CoroutineWorker
จัดทุกอย่างให้เป็นระเบียบอยู่เสมอด้วยคอลเล็กชัน
บันทึกและจัดหมวดหมู่เนื้อหาตามค่ากำหนดของคุณ
สำหรับผู้ใช้ Kotlin นั้น WorkManager จะให้การสนับสนุนโคโริวทีนอย่างเต็มรูปแบบ หากต้องการเริ่มต้นใช้งาน ให้ใส่ work-runtime-ktx
ในไฟล์ gradle คุณควรขยาย CoroutineWorker
ซึ่งมี doWork()
เวอร์ชันที่ระงับแทนการขยาย Worker
เช่น หากต้องการสร้าง 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
ตรงที่โค้ดนี้ไม่ทำงานใน Executor
ที่ระบุใน Configuration
แต่ค่าเริ่มต้นจะเป็น 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
จะจัดการการหยุดทำงานโดยอัตโนมัติด้วยการยกเลิก coroutine และเผยแพร่สัญญาณการยกเลิก คุณไม่จำเป็นต้องดำเนินการใดๆ เป็นพิเศษเพื่อจัดการการหยุดทำงาน
การเรียกใช้ CoroutineWorker ในกระบวนการอื่น
นอกจากนี้ คุณยังเชื่อมโยงผู้ปฏิบัติงานกับกระบวนการที่เฉพาะเจาะจงได้โดยใช้ RemoteCoroutineWorker
ซึ่งเป็นการใช้งาน ListenableWorker
RemoteCoroutineWorker
จะเชื่อมโยงกับกระบวนการที่เฉพาะเจาะจงด้วยอาร์กิวเมนต์เพิ่มเติม 2 รายการที่คุณระบุไว้เป็นส่วนหนึ่งของข้อมูลอินพุตเมื่อสร้างคำขอแจ้งปัญหา นั่นคือ 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 และ/หรือบริษัทในเครือ
อัปเดตล่าสุด 2025-07-27 UTC
[[["เข้าใจง่าย","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"]],["อัปเดตล่าสุด 2025-07-27 UTC"],[],[],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```"]]