A.I, Data and Software Engineering

Constraints with Android Worker

C

Sometimes, we want our app to perform some background tasks under certain conditions, such as Battery level or network etc. With Worker and Constraints, we can conveniently achieve that.

The example problem

A worker class that prints a message to the console.

class MyWorker(context: Context, params: WorkerParameters): Worker(context,params) {

    override fun doWork(): Result {

        Log.i(LOG_TAG, "doWork: Tung")

        return Result.success()

    }

}

We want this function doWork executes when the network is available or the battery is not low.

Use Constraints with Worker

To achieve that, in the main activity, we can set these constraints (Line 5) before executing the background process.

private fun runCode() {

    log("Running code")

    val constraints = Constraints.Builder().setRequiresBatteryNotLow(true).setRequiredNetworkType(NetworkType.CONNECTED).build()

    val workRequest = OneTimeWorkRequestBuilder<MyWorker>()

        .setConstraints(constraints).build()

    WorkManager.getInstance(applicationContext).enqueue(workRequest)
}

Test

First, we can turn off the internet connection. Then, we can try to trigger the event using a button in our app.– Nothing happens as there is no network connection.

Turn off the network using Flight Mode

We now turn off the Flight Mode and bingo, just about some second. The worker class will resume the task assigned.

Output after the network is available

Add comment

💬

A.I, Data and Software Engineering

PetaMinds focuses on developing the coolest topics in data science, A.I, and programming, and make them so digestible for everyone to learn and create amazing applications in a short time.

Categories