Android WorkManager Constraints - Run Only if Network Available

March 6, 2020
val WORK_NAME = "backup"

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


val work = OneTimeWorkRequestBuilder<UploadPhotoWorker>()
    .setConstraints(constraints)
    .build()

val manager = WorkManager.getInstance(context)
manager.enqueueUniqueWork(WORK_NAME, ExistingWorkPolicy.REPLACE, work)

If you don’t want to run on Mobile Network (run on wired network only), use NetworkType.UNMETERED.

If you don’t want to run while roadming, use NetworkType.NOT_ROAMING.

If the request if not time-sensitive, you might not want to run when roaming or when battery is slow.

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

References:

This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.