WorkManager: Define Constraints

Schedule tasks only when the device is charging.

In the previous tutorial, we got Android's WorkManager library setup. In this tutorial, we'll go a bit deeper into WorkManager and define Constraints. Let's get started!

See the previous tutorial to set up WorkManager, including what to add to Gradle.

We previously created the following code to fire a WorkManager request.

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

We can add Constraints to specify when the task should be scheduled. If we want the task to be fired only if the device is charging, we can specify that with setRequiresCharging.

        val constraints = Constraints.Builder()
            .setRequiresCharging(true)
            .build()

Next, change downloadPodcast to include the setConstraints method:

        val downloadPodcasts = OneTimeWorkRequestBuilder<DownloadWorker>()
            .setConstraints(constraints)
            .build()

Our completed code now looks like this:


        val constraints = Constraints.Builder()
            .setRequiresCharging(true)
            .build()

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

Now WorkManager will run only if the device is charging. It's as simple as that!

Tracking WorkManager's Progress

More Tutorials

Kotlin Challenge #1

Build a simple contacts manager.

Android Basic Alert Dialog Box
Basic CardView

Basic CardView

Material Design.

Rounded Corners with a Border
Rounded Button in Android Studio

Rounded Button in Android Studio

Create beautiful buttons in XML.

RecyclerView Day 3: Invoicing app

RecyclerView Day 3: Invoicing app

Built with Android Studio and Kotlin.

Build a Ridesharing Android App - Part 1

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.