WorkManager 시작하기
컬렉션을 사용해 정리하기
내 환경설정을 기준으로 콘텐츠를 저장하고 분류하세요.
WorkManager를 사용하기 위해 먼저 라이브러리를 Android 프로젝트로 가져옵니다.
앱의 build.gradle
파일에 다음 종속 항목을 추가합니다.
Groovy
dependencies {
def work_version = "2.10.3"
// (Java only)
implementation "androidx.work:work-runtime:$work_version"
// Kotlin + coroutines
implementation "androidx.work:work-runtime-ktx:$work_version"
// optional - RxJava2 support
implementation "androidx.work:work-rxjava2:$work_version"
// optional - GCMNetworkManager support
implementation "androidx.work:work-gcm:$work_version"
// optional - Test helpers
androidTestImplementation "androidx.work:work-testing:$work_version"
// optional - Multiprocess support
implementation "androidx.work:work-multiprocess:$work_version"
}
Kotlin
dependencies {
val work_version = "2.10.3"
// (Java only)
implementation("androidx.work:work-runtime:$work_version")
// Kotlin + coroutines
implementation("androidx.work:work-runtime-ktx:$work_version")
// optional - RxJava2 support
implementation("androidx.work:work-rxjava2:$work_version")
// optional - GCMNetworkManager support
implementation("androidx.work:work-gcm:$work_version")
// optional - Test helpers
androidTestImplementation("androidx.work:work-testing:$work_version")
// optional - Multiprocess support
implementation("androidx.work:work-multiprocess:$work_version")
}
종속 항목을 추가하고 Gradle 프로젝트를 동기화했으면 다음으로 실행할 작업을 정의합니다.
작업 정의
작업은 Worker
클래스를 사용하여 정의합니다. doWork()
메서드는 WorkManager에서 제공하는 백그라운드 스레드에서 비동기적으로 실행됩니다.
WorkManager에서 실행할 작업을 만들려면 Worker
클래스를 확장하고 doWork()
메서드를 재정의합니다. 예를 들어 이미지를 업로드하는 Worker
를 만들려면 다음과 같이 할 수 있습니다.
Kotlin
class UploadWorker(appContext: Context, workerParams: WorkerParameters):
Worker(appContext, workerParams) {
override fun doWork(): Result {
// Do the work here--in this case, upload the images.
uploadImages()
// Indicate whether the work finished successfully with the Result
return Result.success()
}
}
자바
public class UploadWorker extends Worker {
public UploadWorker(
@NonNull Context context,
@NonNull WorkerParameters params) {
super(context, params);
}
@Override
public Result doWork() {
// Do the work here--in this case, upload the images.
uploadImages();
// Indicate whether the work finished successfully with the Result
return Result.success();
}
}
doWork()
에서 반환된 Result
는 작업의 성공 여부를 알려주며 실패한 경우 WorkManager 서비스에 작업을 재시도해야 하는지 알려줍니다.
Result.success()
: 작업이 성공적으로 완료되었습니다.
Result.failure()
: 작업에 실패했습니다.
Result.retry()
: 작업에 실패했으며 재시도 정책에 따라 다른 시점에 시도되어야 합니다.
WorkRequest 만들기
작업을 정의하고 나면 실행을 위해 WorkManager 서비스로 예약해야 합니다. WorkManager에서는 작업을 예약하는 다양한 방법을 제공합니다. 일정한 간격으로 주기적으로 실행되도록 예약하거나 한 번만 실행되도록 예약할 수 있습니다.
어떤 작업 예약 방식을 선택하든 항상 WorkRequest
를 사용합니다. Worker
는 작업 단위를 정의하는 반면 WorkRequest
(및 서브클래스)는 언제, 어떻게 작업이 실행되어야 하는지 정의합니다. 가장 간단한 경우 다음 예와 같이 OneTimeWorkRequest
를 사용하면 됩니다.
Kotlin
val uploadWorkRequest: WorkRequest =
OneTimeWorkRequestBuilder<UploadWorker>()
.build()
자바
WorkRequest uploadWorkRequest =
new OneTimeWorkRequest.Builder(UploadWorker.class)
.build();
시스템에 WorkRequest 제출
마지막으로 enqueue()
메서드를 사용하여 WorkRequest
를 WorkManager
에 제출해야 합니다.
Kotlin
WorkManager
.getInstance(myContext)
.enqueue(uploadWorkRequest)
자바
WorkManager
.getInstance(myContext)
.enqueue(uploadWorkRequest);
작업자가 실행되는 정확한 시간은 WorkRequest
에 사용된 제약조건과 시스템 최적화에 따라 달라집니다.
WorkManager는 이러한 제한사항에 따라 최상의 상태로 작동하도록 설계되었습니다.
다음 단계
이 시작 가이드에서는 기본사항만 간략하게 살펴봅니다. WorkRequest
에는 추가 정보도 포함될 수 있습니다(예: 작업 실행의 제약조건, 작업 입력, 지연, 작업 재시도를 위한 백오프 정책). 다음 섹션 작업 요청 정의에서는 이러한 옵션을 자세히 알아보고 고유 작업 및 반복 작업을 예약하는 방법을 알아봅니다.
추가 리소스
가이드 문서 외에도 시작하는 데 도움이 되는 여러 블로그, Codelab, 코드 샘플이 있습니다.
샘플
- Sunflower: WorkManager를 비롯한 다양한 아키텍처 구성요소의 권장사항을 보여주는 데모 앱
Codelab
블로그
이 페이지에 나와 있는 콘텐츠와 코드 샘플에는 콘텐츠 라이선스에서 설명하는 라이선스가 적용됩니다. 자바 및 OpenJDK는 Oracle 및 Oracle 계열사의 상표 또는 등록 상표입니다.
최종 업데이트: 2025-07-30(UTC)
[null,null,["최종 업데이트: 2025-07-30(UTC)"],[],[],null,["# Getting started with WorkManager\n\nTo get started using WorkManager, first import the library into your Android\nproject.\n\nAdd the following dependencies to your app's `build.gradle` file: \n\n### Groovy\n\n```groovy\ndependencies {\n def work_version = \"2.10.3\"\n\n // (Java only)\n implementation \"androidx.work:work-runtime:$work_version\"\n\n // Kotlin + coroutines\n implementation \"androidx.work:work-runtime-ktx:$work_version\"\n\n // optional - RxJava2 support\n implementation \"androidx.work:work-rxjava2:$work_version\"\n\n // optional - GCMNetworkManager support\n implementation \"androidx.work:work-gcm:$work_version\"\n\n // optional - Test helpers\n androidTestImplementation \"androidx.work:work-testing:$work_version\"\n\n // optional - Multiprocess support\n implementation \"androidx.work:work-multiprocess:$work_version\"\n}\n```\n\n### Kotlin\n\n```kotlin\ndependencies {\n val work_version = \"2.10.3\"\n\n // (Java only)\n implementation(\"androidx.work:work-runtime:$work_version\")\n\n // Kotlin + coroutines\n implementation(\"androidx.work:work-runtime-ktx:$work_version\")\n\n // optional - RxJava2 support\n implementation(\"androidx.work:work-rxjava2:$work_version\")\n\n // optional - GCMNetworkManager support\n implementation(\"androidx.work:work-gcm:$work_version\")\n\n // optional - Test helpers\n androidTestImplementation(\"androidx.work:work-testing:$work_version\")\n\n // optional - Multiprocess support\n implementation(\"androidx.work:work-multiprocess:$work_version\")\n}\n```\n\nOnce you've added the dependencies and synchronized your Gradle project, the\nnext step is to define some work to run.\n| **Note:** You can always find the latest version of WorkManager, including beta, alpha, and release candidate versions on the [WorkManager releases\n| page](/jetpack/androidx/releases/work).\n\nDefine the work\n---------------\n\nWork is defined using the [Worker](/reference/androidx/work/Worker)\nclass. The `doWork()` method runs asynchronously on a background\nthread provided by WorkManager.\n\nTo create some work for WorkManager to run, extend the `Worker` class and\noverride the `doWork()` method. For example, to create a `Worker` that uploads\nimages, you can do the following: \n\n### Kotlin\n\n```kotlin\nclass UploadWorker(appContext: Context, workerParams: WorkerParameters):\n Worker(appContext, workerParams) {\n override fun doWork(): Result {\n\n // Do the work here--in this case, upload the images.\n uploadImages()\n\n // Indicate whether the work finished successfully with the Result\n return Result.success()\n }\n}\n```\n\n### Java\n\n```java\npublic class UploadWorker extends Worker {\n public UploadWorker(\n @NonNull Context context,\n @NonNull WorkerParameters params) {\n super(context, params);\n }\n\n @Override\n public Result doWork() {\n\n // Do the work here--in this case, upload the images.\n uploadImages();\n\n // Indicate whether the work finished successfully with the Result\n return Result.success();\n }\n}\n```\n\nThe [Result](/reference/androidx/work/ListenableWorker.Result)\nreturned from `doWork()` informs the WorkManager service whether the\nwork succeeded and, in the case of failure, whether or not the work should be\nretried.\n\n- `Result.success()`: The work finished successfully.\n- `Result.failure()`: The work failed.\n- `Result.retry()`: The work failed and should be tried at another time according to its [retry policy](/topic/libraries/architecture/workmanager/how-to/define-work#retries_backoff).\n\nCreate a WorkRequest\n--------------------\n\nOnce your work is defined, it must be scheduled with the WorkManager service in\norder to run. WorkManager offers a lot of flexibility in how you schedule your\nwork. You can schedule it to [run\nperiodically](/topic/libraries/architecture/workmanager/how-to/define-work#schedule_periodic_work)\nover an interval of time, or you can schedule it to run only [one\ntime](/topic/libraries/architecture/workmanager/how-to/define-work#constraints).\n\nHowever you choose to schedule the work, you will always use a\n[WorkRequest](/reference/androidx/work/WorkRequest). While a\n`Worker` defines the unit of work, a\n[WorkRequest](/reference/androidx/work/WorkRequest) (and its\nsubclasses) define how and when it should be run. In the simplest case, you can\nuse a\n[OneTimeWorkRequest](/reference/androidx/work/OneTimeWorkRequest),\nas shown in the following example. \n\n### Kotlin\n\n```kotlin\nval uploadWorkRequest: WorkRequest =\n OneTimeWorkRequestBuilder\u003cUploadWorker\u003e()\n .build()\n```\n\n### Java\n\n```java\nWorkRequest uploadWorkRequest =\n new OneTimeWorkRequest.Builder(UploadWorker.class)\n .build();\n```\n\nSubmit the WorkRequest to the system\n------------------------------------\n\nFinally, you need to submit your `WorkRequest` to `WorkManager` using the\n[enqueue()](/reference/androidx/work/WorkManager#enqueue(androidx.work.WorkRequest))\nmethod. \n\n### Kotlin\n\n```kotlin\nWorkManager\n .getInstance(myContext)\n .enqueue(uploadWorkRequest)\n```\n\n### Java\n\n```java\nWorkManager\n .getInstance(myContext)\n .enqueue(uploadWorkRequest);\n```\n\nThe exact time that the worker is going to be executed depends on the\nconstraints that are used in your `WorkRequest` and on system optimizations.\nWorkManager is designed to give the best behavior under these restrictions.\n\nNext steps\n----------\n\nThis getting started guide only scratches the surface. The `WorkRequest` can\nalso include additional information, such as the constraints under which the\nwork should run, input to the work, a delay, and backoff policy for retrying\nwork. In the next section, [Define your work\nrequests](/topic/libraries/architecture/workmanager/how-to/define-work), you'll\nlearn more about these options in greater detail as well as get an understanding\nof how to schedule unique and reoccurring work.\n\nAdditional resources\n--------------------\n\nIn addition to guide documentation, there are several blogs, codelabs, and code\nsamples available to help you get started.\n\n### Samples\n\n- [Sunflower](https://github.com/android/sunflower), a demo app demonstrating best practices with various architecture components, including WorkManager.\n\n### Codelabs\n\n- Working with WorkManager [(Kotlin)](https://codelabs.developers.google.com/codelabs/android-workmanager/#0) and [(Java)](https://codelabs.developers.google.com/codelabs/android-workmanager-java/#0)\n- [Advanced WorkManager (Kotlin)](https://codelabs.developers.google.com/codelabs/android-adv-workmanager/#0)\n\n### Blogs\n\n- [Introducing WorkManager](https://medium.com/androiddevelopers/introducing-workmanager-2083bcfc4712)\n- [WorkManager Basics](https://medium.com/androiddevelopers/workmanager-basics-beba51e94048)\n- [WorkManager and Kotlin](https://medium.com/androiddevelopers/workmanager-meets-kotlin-b9ad02f7405e)\n- [WorkManager Periodicity](https://medium.com/androiddevelopers/workmanager-periodicity-ff35185ff006)\n- [Customizing WorkManager - Fundamentals](https://medium.com/androiddevelopers/customizing-workmanager-fundamentals-fdaa17c46dd2)\n- [Customize WorkManager with Dagger](https://medium.com/androiddevelopers/customizing-workmanager-with-dagger-1029688c0978)"]]