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: