Android Background Task Specialist
Expert in Android background execution with WorkManager, Foreground Services, Doze mode handling, and battery-efficient processing.
Activation Triggers
Activate on: "WorkManager", "background task Android", "Foreground Service", "Doze mode", "battery optimization", "periodic work", "background sync", "JobScheduler", "background processing Android"
NOT for: iOS background tasks → swiftui-data-flow-expert | React Native background → mobile-offline-sync-architect | UI architecture → jetpack-compose-navigation-expert
Quick Start
- Choose the right API — WorkManager for deferrable work, Foreground Service for user-visible ongoing tasks, coroutines for short async work
- Define workers — extend
CoroutineWorker with suspend functions for clean async code
- Configure constraints — network type, battery level, storage requirements
- Handle Doze and App Standby — use WorkManager (not AlarmManager) for Doze-compatible scheduling
- Test with adb — force Doze mode and verify work executes when constraints are met
Core Capabilities
| Domain |
Technologies |
| Deferrable Work |
WorkManager 2.10, OneTimeWorkRequest, PeriodicWorkRequest |
| Foreground |
Foreground Service types (dataSync, location, mediaPlayback, shortService) |
| Constraints |
NetworkType, BatteryNotLow, StorageNotLow, DeviceIdle |
| Chaining |
WorkContinuation, parallel chains, unique work policies |
| Testing |
TestWorkerBuilder, TestListenableWorkerBuilder, WorkManagerTestInitHelper |
Architecture Patterns
WorkManager Decision Tree
Is the task user-initiated and needs to complete?
├─ YES → Is it short (< 10 min)?
│ ├─ YES → Foreground Service (shortService type)
│ └─ NO → Foreground Service (dataSync, location, etc.)
│
└─ NO → Is it deferrable?
├─ YES → WorkManager
│ ├─ One-time? → OneTimeWorkRequest
│ └─ Periodic? → PeriodicWorkRequest (min 15 min interval)
│
└─ NO → Is it while app is visible?
├─ YES → CoroutineScope (viewModelScope or lifecycleScope)
└─ NO → You probably need WorkManager anyway
CoroutineWorker with Retry and Progress
@HiltWorker
class SyncWorker @AssistedInject constructor(
@Assisted context: Context,
@Assisted params: WorkerParameters,
private val syncRepository: SyncRepository,
private val notificationHelper: NotificationHelper,
) : CoroutineWorker(context, params) {
override suspend fun doWork(): Result {
// Report progress for UI observation
setProgress(workDataOf("progress" to 0))
return try {
val pendingItems = syncRepository.getPendingChanges()
pendingItems.forEachIndexed { index, item ->
syncRepository.syncItem(item)
setProgress(workDataOf(
"progress" to ((index + 1) * 100 / pendingItems.size)
))
}
Result.success(workDataOf("synced" to pendingItems.size))
} catch (e: IOException) {
if (runAttemptCount < 3) {
Result.retry() // Exponential backoff by default
} else {
Result.failure(workDataOf("error" to e.message))
}
}
}
override suspend fun getForegroundInfo(): ForegroundInfo {
return ForegroundInfo(
NOTIFICATION_ID,
notificationHelper.createSyncNotification()
)
}
}
Scheduling with Constraints and Chaining
// Schedule periodic sync every 1 hour (minimum 15 min)
val syncRequest = PeriodicWorkRequestBuilder<SyncWorker>(1, TimeUnit.HOURS)
.setConstraints(
Constraints.Builder()
.setRequiredNetworkType(NetworkType.CONNECTED)
.setRequiresBatteryNotLow(true)
.build()
)
.setBackoffCriteria(
BackoffPolicy.EXPONENTIAL,
WorkRequest.MIN_BACKOFF_MILLIS,
TimeUnit.MILLISECONDS
)
.addTag("sync")
.build()
WorkManager.getInstance(context).enqueueUniquePeriodicWork(
"periodic-sync",
ExistingPeriodicWorkPolicy.KEEP, // Don't restart if already scheduled
syncRequest
)
// Chain: download → process → upload (sequential)
WorkManager.getInstance(context)
.beginWith(downloadWork)
.then(processWork)
.then(uploadWork)
.enqueue()
Anti-Patterns
- AlarmManager for deferrable work — AlarmManager alarms are not Doze-compatible and drain battery. Use WorkManager which respects Doze, App Standby, and battery saver.
- Background Service without foreground notification — Android 12+ kills background services. Use Foreground Service with proper type declaration or WorkManager.
- PeriodicWork under 15 minutes — WorkManager enforces a minimum 15-minute interval. For more frequent work, use Foreground Service or coroutine with lifecycle awareness.
- Not declaring foreground service type — Android 14+ requires explicit
foregroundServiceType in manifest. Omitting it causes SecurityException.
- Ignoring work observation — starting work but not showing progress to users. Observe
WorkInfo via getWorkInfoByIdLiveData() or getWorkInfoByIdFlow() to update UI.
Quality Checklist
[ ] WorkManager used for deferrable background tasks (not AlarmManager)
[ ] Foreground Service declared with correct type in AndroidManifest
[ ] Constraints configured (network, battery, storage)
[ ] Retry policy with backoff for transient failures
[ ] Unique work policy set for periodic/one-time work
[ ] Work progress observable from UI
[ ] Doze mode tested via adb: `adb shell dumpsys deviceidle force-idle`
[ ] Battery optimization tested: `adb shell am set-inactive <package> true`
[ ] Workers tested with TestWorkerBuilder
[ ] Notification channels created for foreground service notifications
[ ] Work chains handle partial failure gracefully
[ ] Background work respects user's battery saver preference
1---2license: Apache-2.03name: android-background-task-specialist4description: "Android background task specialist for WorkManager, Foreground Services, Doze mode, and battery optimization. Activate on: WorkManager, background task Android, Foreground Service, Doze mode, battery optimization, periodic work, background sync Android, JobScheduler. NOT for: iOS background tasks (use swiftui-data-flow-expert), React Native background (use mobile-offline-sync-architect), UI architecture (use jetpack-compose-navigation-expert)."5allowed-tools: Read,Write,Edit,Bash(gradle:*,adb:*)6category: Mobile Development7tags:8 - android9 - background-tasks10 - workmanager11 - battery12pairs-with:13 - skill: jetpack-compose-navigation-expert14 reason: ViewModels and UI layer coordinate with background task results15 - skill: mobile-offline-sync-architect16 reason: Background sync is a key offline-first pattern on Android17metadata:18 source: https://skillmd.com/skills/curiositech/android-background-task-specialist19---2021# Android Background Task Specialist2223Expert in Android background execution with WorkManager, Foreground Services, Doze mode handling, and battery-efficient processing.2425## Activation Triggers2627**Activate on:** "WorkManager", "background task Android", "Foreground Service", "Doze mode", "battery optimization", "periodic work", "background sync", "JobScheduler", "background processing Android"2829**NOT for:** iOS background tasks → `swiftui-data-flow-expert` | React Native background → `mobile-offline-sync-architect` | UI architecture → `jetpack-compose-navigation-expert`3031## Quick Start32331. **Choose the right API** — WorkManager for deferrable work, Foreground Service for user-visible ongoing tasks, coroutines for short async work342. **Define workers** — extend `CoroutineWorker` with suspend functions for clean async code353. **Configure constraints** — network type, battery level, storage requirements364. **Handle Doze and App Standby** — use WorkManager (not AlarmManager) for Doze-compatible scheduling375. **Test with adb** — force Doze mode and verify work executes when constraints are met3839## Core Capabilities4041| Domain | Technologies |42|--------|-------------|43| **Deferrable Work** | WorkManager 2.10, OneTimeWorkRequest, PeriodicWorkRequest |44| **Foreground** | Foreground Service types (dataSync, location, mediaPlayback, shortService) |45| **Constraints** | NetworkType, BatteryNotLow, StorageNotLow, DeviceIdle |46| **Chaining** | WorkContinuation, parallel chains, unique work policies |47| **Testing** | TestWorkerBuilder, TestListenableWorkerBuilder, WorkManagerTestInitHelper |4849## Architecture Patterns5051### WorkManager Decision Tree5253```54Is the task user-initiated and needs to complete?55 ├─ YES → Is it short (< 10 min)?56 │ ├─ YES → Foreground Service (shortService type)57 │ └─ NO → Foreground Service (dataSync, location, etc.)58 │59 └─ NO → Is it deferrable?60 ├─ YES → WorkManager61 │ ├─ One-time? → OneTimeWorkRequest62 │ └─ Periodic? → PeriodicWorkRequest (min 15 min interval)63 │64 └─ NO → Is it while app is visible?65 ├─ YES → CoroutineScope (viewModelScope or lifecycleScope)66 └─ NO → You probably need WorkManager anyway67```6869### CoroutineWorker with Retry and Progress7071```kotlin72@HiltWorker73class SyncWorker @AssistedInject constructor(74 @Assisted context: Context,75 @Assisted params: WorkerParameters,76 private val syncRepository: SyncRepository,77 private val notificationHelper: NotificationHelper,78) : CoroutineWorker(context, params) {7980 override suspend fun doWork(): Result {81 // Report progress for UI observation82 setProgress(workDataOf("progress" to 0))8384 return try {85 val pendingItems = syncRepository.getPendingChanges()8687 pendingItems.forEachIndexed { index, item ->88 syncRepository.syncItem(item)89 setProgress(workDataOf(90 "progress" to ((index + 1) * 100 / pendingItems.size)91 ))92 }9394 Result.success(workDataOf("synced" to pendingItems.size))95 } catch (e: IOException) {96 if (runAttemptCount < 3) {97 Result.retry() // Exponential backoff by default98 } else {99 Result.failure(workDataOf("error" to e.message))100 }101 }102 }103104 override suspend fun getForegroundInfo(): ForegroundInfo {105 return ForegroundInfo(106 NOTIFICATION_ID,107 notificationHelper.createSyncNotification()108 )109 }110}111```112113### Scheduling with Constraints and Chaining114115```kotlin116// Schedule periodic sync every 1 hour (minimum 15 min)117val syncRequest = PeriodicWorkRequestBuilder<SyncWorker>(1, TimeUnit.HOURS)118 .setConstraints(119 Constraints.Builder()120 .setRequiredNetworkType(NetworkType.CONNECTED)121 .setRequiresBatteryNotLow(true)122 .build()123 )124 .setBackoffCriteria(125 BackoffPolicy.EXPONENTIAL,126 WorkRequest.MIN_BACKOFF_MILLIS,127 TimeUnit.MILLISECONDS128 )129 .addTag("sync")130 .build()131132WorkManager.getInstance(context).enqueueUniquePeriodicWork(133 "periodic-sync",134 ExistingPeriodicWorkPolicy.KEEP, // Don't restart if already scheduled135 syncRequest136)137138// Chain: download → process → upload (sequential)139WorkManager.getInstance(context)140 .beginWith(downloadWork)141 .then(processWork)142 .then(uploadWork)143 .enqueue()144```145146## Anti-Patterns1471481. **AlarmManager for deferrable work** — AlarmManager alarms are not Doze-compatible and drain battery. Use WorkManager which respects Doze, App Standby, and battery saver.1492. **Background Service without foreground notification** — Android 12+ kills background services. Use Foreground Service with proper type declaration or WorkManager.1503. **PeriodicWork under 15 minutes** — WorkManager enforces a minimum 15-minute interval. For more frequent work, use Foreground Service or coroutine with lifecycle awareness.1514. **Not declaring foreground service type** — Android 14+ requires explicit `foregroundServiceType` in manifest. Omitting it causes `SecurityException`.1525. **Ignoring work observation** — starting work but not showing progress to users. Observe `WorkInfo` via `getWorkInfoByIdLiveData()` or `getWorkInfoByIdFlow()` to update UI.153154## Quality Checklist155156```157[ ] WorkManager used for deferrable background tasks (not AlarmManager)158[ ] Foreground Service declared with correct type in AndroidManifest159[ ] Constraints configured (network, battery, storage)160[ ] Retry policy with backoff for transient failures161[ ] Unique work policy set for periodic/one-time work162[ ] Work progress observable from UI163[ ] Doze mode tested via adb: `adb shell dumpsys deviceidle force-idle`164[ ] Battery optimization tested: `adb shell am set-inactive <package> true`165[ ] Workers tested with TestWorkerBuilder166[ ] Notification channels created for foreground service notifications167[ ] Work chains handle partial failure gracefully168[ ] Background work respects user's battery saver preference169```