paint-brush
Running Background Tasks in Android with WorkManager: Part 2by@azamatnurkhojayev
347 reads
347 reads

Running Background Tasks in Android with WorkManager: Part 2

by Azamat NurkhojayevApril 20th, 2023
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

WorkManager allows us to set the constraint for launching a task, for example, whether the Internet is on the device. When you pass such a task to WorkManager.enqueue, it will check that there is an internet connection.
featured image - Running Background Tasks in Android with WorkManager: Part 2
Azamat Nurkhojayev HackerNoon profile picture

Previous article in this series: Running Background Tasks in Android with WorkManager: Part 1

Task start constraint

WorkManager allows us to set the constraint for launching a task. For example, the task in question could be checking whether there’s Internet service on the device. When you pass such a task to WorkManager.enqueue, it will check that there is an internet connection. If there is a connection, then the task will start. And if there isn’t, then the task will hang in the ENQUEUED status until the Internet appears.


If the task is running and the Internet is lost for some reason, the task will be stopped and scheduled again (ENQUEUED).


Let's look at what constraint we can set.


For example, we will use such a task.

class WorkManager (context: Context, parameters: WorkerParameters) : Worker(context, parameters) {  

    private val TAG = this.javaClass.simpleName  

    override fun doWork(): Result {  

        Log.d(TAG, "doWork: start")  

        try {  

            (0 .. 10).forEach {  

                TimeUnit.SECONDS.sleep(10)  

                Log.d(TAG, "${it}, isStopped: $isStopped")  

                if (isStopped)  

                    return Result.failure()  

            }  

        } catch (e: InterruptedException) {  

            e.printStackTrace()  

        }  

        Log.d(TAG, "doWork: end")  

        return Result.success()  

    }  

    override fun onStopped() {  

        super.onStopped()  

        Log.d(TAG, "onStopped: ")  

    }  

}


Loop 10 pauses and log the isStopped status. If the task was stopped, then exit with the FAILURE status.


We also log the onStopped method.


In the Activity, the code below is used to track the status of a task:

WorkManager.getInstance(this)  

    .getWorkInfoByIdLiveData(workRequest.id)  

    .observe(this) { workInfo ->  

        Log.d(TAG, "onChanged: " + workInfo.state)  

    }


setRequiresCharging (boolean requiresCharging)

Constraint: The charger must be connected.


The code for adding a constraint looks like this:

val constraints = Constraints.Builder()  

    .setRequiresCharging(true)  

    .build()  

val workRequest: WorkRequest = OneTimeWorkRequestBuilder<MyWorker>()  

    .setConstraints(constraints)  

    .build()


In Constraints.Builder, we include the setRequiresCharging criterion, create a Constraints object and pass it to OneTimeWorkRequest.Builder in the setConstraints method.


setRequiresBatteryNotLow (boolean requiresBatteryNotLow)

Constraint: the battery level is not lower than critical.


setRequiredNetworkType(NetworkType networkType)

Constraint: the presence of the Internet.


We can specify what type of Internet network (NetworkType) should be used when starting the task:

CONNECTED - WiFi or Mobile Data UNMETERED - WiFi only METERED - Mobile Data only NOT_ROAMING - Internet must not be roaming NOT_REQUIRED - Internet is not required


setRequiresDeviceIdle (boolean requiresDeviceIdle)

Constraint: the device has not been used for some time and has gone into hibernation. Works on API 23 and up.


setRequiresStorageNotLow (boolean requiresStorageNotLow)

Constraint: there must be free space on the device, not less than the critical threshold.


addContentUriTrigger(Uri uri, boolean triggerForDescendants)

Constraint: The task will run when the content of the specified Uri is updated. Works on API 24 and above.


For one task, you can set several constraints at once.