Android WorkManager Constraints — Complete Guide
In this tutorial, you'll learn about Android WorkManager Constraints. We cover key concepts, practical examples, and best practices to help you understand and apply this topic effectively.
The Problem
Your worker runs without WiFi and burns the user's mobile data. Or it runs while the battery is low and the user misses an important notification because the device shut down.
Wrong Approach ❌
// No constraints — runs immediately regardless of conditions
val request = OneTimeWorkRequestBuilder<DataSyncWorker>()
.build()
WorkManager.getInstance(context).enqueue(request)
Output: Worker runs on mobile data, drains battery, runs during low battery.
Right Approach ✅
val constraints = Constraints.Builder()
.setRequiredNetworkType(NetworkType.UNMETERED) // WiFi only
.setRequiresBatteryNotLow(true) // Battery > low threshold
.setRequiresCharging(false) // Optional: charging only
.setRequiresDeviceIdle(true) // Optional: doze mode only
.setRequiresStorageNotLow(true) // Optional: enough storage
.build()
val request = OneTimeWorkRequestBuilder<DataSyncWorker>()
.setConstraints(constraints)
.build()
WorkManager.getInstance(context).enqueue(request)
Output: Worker runs only on WiFi, with sufficient battery and storage.
Prevention
- Always set
NetworkType.UNMETEREDfor large data transfers. - Set
setRequiresBatteryNotLow(true)for CPU-intensive work. - Set
setRequiresDeviceIdle(true)for work that can wait. - Combine constraints — a single missing constraint can cause early execution.
Common Mistakes with workmanager constraint
- Mixing let bindings with <- bindings in do notation, producing type errors
- Overlapping type class instances that cause GHC to reject the program with ambiguous dispatch errors
- Non-exhaustive pattern matches that compile with warnings then crash at runtime
These mistakes appear frequently in real-world Android code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro