Android WorkManager: Getting Started

Get up and running with WorkManager.

Let's build a podcasting app that will download new episodes every day around 2am.

As is usual for most libraries, we need to add a Gradle dependency in our build.gradle file.
    implementation "androidx.work:work-runtime-ktx:2.0.0"

We need to create a new class that extends Worker. In this case, I called the new class DownloadWorker, but it can be called anything. It takes a Context and WorkerParameters as parameters.

class DownloadWorker(appContext: Context, params: WorkerParameters) : Worker(appContext, params) {
}

With that in place, let's implement the required method doWork. This is done on a background thread.

package com.example.workmanager

import android.content.Context
import android.util.Log.d
import androidx.work.Worker
import androidx.work.WorkerParameters

class DownloadWorker(appContext: Context, params: WorkerParameters) : Worker(appContext, params) {

    override fun doWork(): Result {

        d("daniel", "downloading new episodes now...")
        return Result.success()
    }
}

Inside MainActivity.kt we need to actually trigger this WorkManager task. Inside of onCreate, write:

        val downloadPodcasts = OneTimeWorkRequestBuilder<DownloadWorker>().build()
        WorkManager.getInstance().enqueue(downloadPodcasts)

Run the app, open the Logcat and you should see the following:

2019-03-29 16:04:55.228 14602-14633/? D/daniel: downloading new episodes now...

That's the basics of WorkManager on Android! Stay tuned for next week's tutorial on adding Constraints to the WorkManager class, such as only downloading podcast episodes if the device is idle and on WiFi (not cellular data).

WorkManager: Define Constraints

More Tutorials

Build a Ridesharing Android App - Part 1

Getting started is sometimes the hardest part.

setOnClickListener

Add a click listener in Kotlin.

Android Login Layout

Let users sign in.