Threader di Worker
Tetap teratur dengan koleksi
Simpan dan kategorikan konten berdasarkan preferensi Anda.
Saat Anda menggunakan Worker
, WorkManager
otomatis memanggil Worker.doWork()
pada thread latar belakang. Thread latar belakang berasal dari Executor
yang ditentukan dalam Configuration
WorkManager.
Secara default, WorkManager menyiapkan Executor
untuk Anda - tetapi Anda juga dapat menyesuaikannya
sendiri. Misalnya, Anda dapat membagikan Executor latar belakang yang ada dalam
aplikasi, membuat Executor
thread tunggal untuk memastikan semua pekerjaan
latar belakang dijalankan berurutan, atau bahkan menentukan Executor
kustom. Untuk menyesuaikan
Executor
, pastikan Anda menginisialisasi WorkManager secara manual.
Saat mengonfigurasi WorkManager secara manual, Anda dapat menentukan Executor
sebagai
berikut:
Kotlin
WorkManager.initialize(
context,
Configuration.Builder()
// Uses a fixed thread pool of size 8 threads.
.setExecutor(Executors.newFixedThreadPool(8))
.build())
Java
WorkManager.initialize(
context,
new Configuration.Builder()
.setExecutor(Executors.newFixedThreadPool(8))
.build());
Berikut adalah contoh Worker
sederhana yang mendownload konten halaman web
100 kali:
Kotlin
class DownloadWorker(context: Context, params: WorkerParameters) : Worker(context, params) {
override fun doWork(): ListenableWorker.Result {
repeat(100) {
try {
downloadSynchronously("https://www.google.com")
} catch (e: IOException) {
return ListenableWorker.Result.failure()
}
}
return ListenableWorker.Result.success()
}
}
Java
public class DownloadWorker extends Worker {
public DownloadWorker(Context context, WorkerParameters params) {
super(context, params);
}
@NonNull
@Override
public Result doWork() {
for (int i = 0; i < 100; i++) {
try {
downloadSynchronously("https://www.google.com");
} catch (IOException e) {
return Result.failure();
}
}
return Result.success();
}
}
Ingat bahwa Worker.doWork()
merupakan
panggilan sinkron - Anda diharapkan melakukan seluruh pekerjaan
latar belakang secara tertutup dan menyelesaikannya sebelum metode ditutup. Jika Anda memanggil
API asinkron di doWork()
dan menampilkan Result
, callback mungkin tidak
beroperasi dengan benar. Jika Anda berada dalam situasi ini, pertimbangkan untuk menggunakan ListenableWorker
(lihat Threading di ListenableWorker).
Jika Worker
yang sedang berjalan dihentikan karena suatu alasan,
maka worker akan menerima panggilan ke Worker.onStopped()
. Ganti metode ini atau
panggil Worker.isStopped()
untuk memeriksa kode Anda dan mengosongkan resource, jika perlu. Jika Worker
pada
contoh di atas dihentikan, worker tersebut mungkin berada di tengah-tengah
proses mendownload item dan akan terus mendownload item meskipun telah dihentikan. Untuk
mengoptimalkan perilaku ini, Anda bisa melakukannya seperti berikut:
Kotlin
class DownloadWorker(context: Context, params: WorkerParameters) : Worker(context, params) {
override fun doWork(): ListenableWorker.Result {
repeat(100) {
if (isStopped) {
break
}
try {
downloadSynchronously("https://www.google.com")
} catch (e: IOException) {
return ListenableWorker.Result.failure()
}
}
return ListenableWorker.Result.success()
}
}
Java
public class DownloadWorker extends Worker {
public DownloadWorker(Context context, WorkerParameters params) {
super(context, params);
}
@NonNull
@Override
public Result doWork() {
for (int i = 0; i < 100; ++i) {
if (isStopped()) {
break;
}
try {
downloadSynchronously("https://www.google.com");
} catch (IOException e) {
return Result.failure();
}
}
return Result.success();
}
}
Setelah Worker
dihentikan, apa pun yang Anda kembalikan dari
Worker.doWork()
tidak penting lagi; Result
akan diabaikan.
Konten dan contoh kode di halaman ini tunduk kepada lisensi yang dijelaskan dalam Lisensi Konten. Java dan OpenJDK adalah merek dagang atau merek dagang terdaftar dari Oracle dan/atau afiliasinya.
Terakhir diperbarui pada 2025-07-27 UTC.
[[["Mudah dipahami","easyToUnderstand","thumb-up"],["Memecahkan masalah saya","solvedMyProblem","thumb-up"],["Lainnya","otherUp","thumb-up"]],[["Informasi yang saya butuhkan tidak ada","missingTheInformationINeed","thumb-down"],["Terlalu rumit/langkahnya terlalu banyak","tooComplicatedTooManySteps","thumb-down"],["Sudah usang","outOfDate","thumb-down"],["Masalah terjemahan","translationIssue","thumb-down"],["Masalah kode / contoh","samplesCodeIssue","thumb-down"],["Lainnya","otherDown","thumb-down"]],["Terakhir diperbarui pada 2025-07-27 UTC."],[],[],null,["# Threading in Worker\n\nWhen you use a [`Worker`](/reference/androidx/work/Worker), WorkManager\nautomatically calls [`Worker.doWork()`](/reference/androidx/work/Worker#doWork())\non a background thread. The background thread comes from the `Executor`\nspecified in WorkManager's [`Configuration`](/reference/androidx/work/Configuration).\nBy default, WorkManager sets up an `Executor` for you---but you can also customize\nyour own. For example, you can share an existing background Executor in your\napp, create a single-threaded `Executor` to make sure all your background work\nexecutes sequentially, or even specify a custom `Executor`. To customize the\n`Executor`, make sure you initialize WorkManager manually.\n\nWhen configuring WorkManager manually, you can specify your `Executor` as\nfollows: \n\n### Kotlin\n\n```kotlin\nWorkManager.initialize(\n context,\n Configuration.Builder()\n // Uses a fixed thread pool of size 8 threads.\n .setExecutor(Executors.newFixedThreadPool(8))\n .build())\n```\n\n### Java\n\n```java\nWorkManager.initialize(\n context,\n new Configuration.Builder()\n .setExecutor(Executors.newFixedThreadPool(8))\n .build());\n```\n\nHere is an example of a simple `Worker` that downloads the contents of a webpage\n100 times: \n\n### Kotlin\n\n```kotlin\nclass DownloadWorker(context: Context, params: WorkerParameters) : Worker(context, params) {\n\n override fun doWork(): ListenableWorker.Result {\n repeat(100) {\n try {\n downloadSynchronously(\"https://www.google.com\")\n } catch (e: IOException) {\n return ListenableWorker.Result.failure()\n }\n }\n\n return ListenableWorker.Result.success()\n }\n}\n```\n\n### Java\n\n```java\npublic class DownloadWorker extends Worker {\n\n public DownloadWorker(Context context, WorkerParameters params) {\n super(context, params);\n }\n\n @NonNull\n @Override\n public Result doWork() {\n for (int i = 0; i \u003c 100; i++) {\n try {\n downloadSynchronously(\"https://www.google.com\");\n } catch (IOException e) {\n return Result.failure();\n }\n }\n\n return Result.success();\n }\n\n}\n```\n\nNote that [`Worker.doWork()`](/reference/androidx/work/Worker#doWork()) is a\nsynchronous call---you are expected to do the entirety of your background work in\na blocking fashion and finish it by the time the method exits. If you call an\nasynchronous API in `doWork()` and return a [`Result`](/reference/androidx/work/ListenableWorker.Result), your callback may not\noperate properly. If you find yourself in this situation, consider using a [`ListenableWorker`](/reference/androidx/work/ListenableWorker) (see [Threading in ListenableWorker](/topic/libraries/architecture/workmanager/advanced/listenableworker)).\n\nWhen a currently running `Worker` is [stopped for any reason](/topic/libraries/architecture/workmanager/how-to/managing-work#cancelling), it\nreceives a call to [`Worker.onStopped()`](/reference/androidx/work/ListenableWorker#onStopped()). Override this method or\ncall [`Worker.isStopped()`](/reference/androidx/work/ListenableWorker#isStopped())\nto checkpoint your code and free up resources when necessary. When the `Worker`\nin the example above is stopped, it may be in the middle of its loop of\ndownloading items and will continue doing so even though it has been stopped. To\noptimize this behavior, you can do something like this: \n\n### Kotlin\n\n```kotlin\nclass DownloadWorker(context: Context, params: WorkerParameters) : Worker(context, params) {\n\n override fun doWork(): ListenableWorker.Result {\n repeat(100) {\n if (isStopped) {\n break\n }\n\n try {\n downloadSynchronously(\"https://www.google.com\")\n } catch (e: IOException) {\n return ListenableWorker.Result.failure()\n }\n\n }\n\n return ListenableWorker.Result.success()\n }\n}\n```\n\n### Java\n\n```java\npublic class DownloadWorker extends Worker {\n\n public DownloadWorker(Context context, WorkerParameters params) {\n super(context, params);\n }\n\n @NonNull\n @Override\n public Result doWork() {\n for (int i = 0; i \u003c 100; ++i) {\n if (isStopped()) {\n break;\n }\n\n try {\n downloadSynchronously(\"https://www.google.com\");\n } catch (IOException e) {\n return Result.failure();\n }\n }\n\n return Result.success();\n }\n}\n```\n\nOnce a `Worker` has been stopped, it doesn't matter what you return from\n`Worker.doWork()`; the `Result` will be ignored."]]