TheJadav

Wrok constraints in android work manager

Wrok constraints in android work manager

In this post we will see different constraint which we can set when requesting work manager to do work.

NetworkType

Available options for network type is listed below, we can use any of constraint based on our requirement like  call api only when connected to network, or download large data when network unmetered.

  • CONNECTED : Connected to any network
  • METERED: 
  • NOT_REQUIRED
  • NOT_ROAMING
  • TEMPORARILY_UNMETERED
  • UNMETERED 

BatteryNotLow

when we set this parameter to true, work will not work if battery is low. 

RequiresCharging

This parameter checks device charging state and only execute work if it is in charging.

DeviceIdle

This ensures that device is not in use by user. This helps to ensure our resources are not used by other apps when we are executing work. 

StorageNotLow

This parameter checks storage availability in device and if it is set to true then it will only execute when device not running on low space.

here is simple demo to use constraint:

val constraints = Constraints.Builder()
.setRequiredNetworkType(NetworkType.UNMETERED)
.setRequiresCharging(true)
.build()

val myWorkRequest: WorkRequest =
OneTimeWorkRequestBuilder<MyWork>()
.setConstraints(constraints)
.build()

Thank you for reading this. 

Will post next update soon

Share this content:

Share:

More Posts

How does data persistence work in Android?

Data persistence in Android is the ability to save data to the device so that it can be accessed later, even if the app is closed or the device is restarted. There are several ways to achieve data persistence in Android

Fragments and Activities: Two Pillars of Android Development

Fragments and Activities are both important components of Android development. Fragments are a good choice for creating reusable and dynamic UIs, while Activities are a good choice for managing the lifecycle of an app’s UI and implementing core features.

Table of Contents

Send Us A Message