Android WorkManager Tutorial For Beginner in Kotlin

Hello friends,
Today i am discussing about WorkManager in Kotlin, i tried using a couple of days ago.

if you are new to kotlin refer here.

What is WorkManager?

WorkManager API is designed to run task after particular time in favorable conditions.

Benefits of WorkManager.

  • Backwards compatible up to API 14
  • Add work constraints like network availability or charging status
  • Schedule asynchronous one-off or periodic tasks
  • Monitor and manage scheduled tasks
  • Chain tasks together
  • Ensures task execution, even if the app or device restarts
  • Adheres to power-saving features like Doze mode

Talk is cheap show me the Code

First of all implement the library.

If you are using Androidx then use following dependency.

implementation 'androidx.work:work-runtime-ktx:2.0.1'

without Androidx use

implementation 'android.arch.work:work-runtime:1.0.1'

Note: v1 is used for Projects without Androidx & v2 for Androidx projects.

Real game begins here first of all we create our worker class which is executed when the conditions meet.

Create a class named UploadWorker extends Worker.

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 task finished successfully with the Result
        return Result.success()
    }
}

Now the main work begins here, Tell WorkManager to perform the task.

val oneTimeWorkRequest = OneTimeWorkRequest.Builder(UploadWorker::class.java).build()
WorkManager.getInstance(Context).enqueue(oneTimeWorkRequest)

You can also put a Condition like this.


// Create a Constraints object that defines when the task should run
val constraints = Constraints.Builder()
        .setRequiresDeviceIdle(true)
        .setRequiresCharging(true)
        .build()

// ...then create a OneTimeWorkRequest that uses those constraints
val compressionWork = OneTimeWorkRequestBuilder<CompressWorker>()
        .setConstraints(constraints)
        .build()

Here we go our first tutorial ends.
Try more code, Learn more.

Any problem in android comment below. <3

Leave a Reply