Background work cheat sheet
Key ideas
- Choose by guarantee: a coroutine in
viewModelScopefor screen-bound work, WorkManager for deferrable work, a foreground service for long user-visible work, an alarm for an exact time. - Periodic WorkManager work runs at least every 15 minutes (not at a fixed clock time); each run gets about 10 minutes before it must yield.
- Call
startForeground()within 5 seconds ofstartForegroundService(); the window starts at the call, not atonStartCommandreturn. - On target 34 a missing
foregroundServiceTypein the manifest throwsMissingForegroundServiceTypeException; add the matchingFOREGROUND_SERVICE_<TYPE>permission too. @HiltWorkerneedsHiltWorkerFactorywired throughConfiguration.Providerand the defaultWorkManagerInitializerremoved from the manifest, or every run fails at runtime.- Create
NotificationChannelobjects at app start; the id is a permanent key for the user's settings and cannot be reset by code. - Exact alarms require
SCHEDULE_EXACT_ALARMaccess; on Android 14 it is denied by default for most new installs, so checkcanScheduleExactAlarms()and fall back to inexact. onReceive()runs on the main thread; usegoAsync()for a few seconds of work or hand off to WorkManager for anything longer or retryable.- All alarms are cleared on reboot and force-stop; persist the schedule and reschedule on
BOOT_COMPLETEDwithRECEIVE_BOOT_COMPLETED. Result.retry()applies the configured backoff;Result.failure()stops the work and fails any chained work; cap retries withrunAttemptCount.
APIs at a glance
| API or term | Use it for |
|---|---|
WorkManager | Enqueue deferrable background work with constraints, retry, and unique-name policies. |
CoroutineWorker | Suspend-based worker; receives CancellationException when constraints fail or work is cancelled. |
PeriodicWorkRequestBuilder | Schedule recurring work; minimum interval is 15 minutes, each run gets ~10 minutes. |
ExistingPeriodicWorkPolicy.KEEP | No-op on re-enqueue; safe to call at every app launch without cancelling running work. |
ServiceCompat.startForeground() / stopForeground() | Promote a service with a ServiceInfo.FOREGROUND_SERVICE_TYPE_* on any API level; stopForeground() replaces the deprecated stopForeground(Boolean). |
NotificationChannel | Permanent user-settings key; create at app start, never churn ids. |
AlarmManager.setExactAndAllowWhileIdle() | Fire at a precise wall-clock time even during Doze; needs exact-alarm access on target 31+. |
BroadcastReceiver.goAsync() | Extend onReceive() for a few seconds; always call pendingResult.finish() in a finally block. |
@HiltWorker | DI annotation for workers; requires HiltWorkerFactory in Configuration.Provider and removal of the default initializer. |
PendingIntent.FLAG_IMMUTABLE | Mutability flag every PendingIntent must state on target 31+; use FLAG_MUTABLE only for RemoteInput or bubbles. |
canScheduleExactAlarms() | Check exact-alarm access before calling setExact(); fall back to setAndAllowWhileIdle() if denied. |
RECEIVER_NOT_EXPORTED / RECEIVER_EXPORTED | Required flag on registerReceiver() for non-system broadcasts at target 34+; omitting it throws SecurityException. |
Snippets
CoroutineWorker with bounded retry
interface SyncRepository { suspend fun sync() }
@HiltWorker
class SyncWorker @AssistedInject constructor(
@Assisted appContext: Context,
@Assisted params: WorkerParameters,
private val repository: SyncRepository,
) : CoroutineWorker(appContext, params) {
override suspend fun doWork(): Result = try {
repository.sync()
Result.success()
} catch (e: IOException) {
if (runAttemptCount < MAX_ATTEMPTS) Result.retry() else Result.failure()
}
companion object {
const val MAX_ATTEMPTS = 3
const val UNIQUE_NAME = "sync"
}
}Foreground service: promote first, stop with ServiceCompat
// Inside a Service that defines ACTION_STOP, NOTIFICATION_ID and buildNotification()
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
if (intent?.action == ACTION_STOP) {
ServiceCompat.stopForeground(this, ServiceCompat.STOP_FOREGROUND_REMOVE)
stopSelf()
return START_NOT_STICKY
}
ServiceCompat.startForeground(
this, NOTIFICATION_ID, buildNotification(),
ServiceInfo.FOREGROUND_SERVICE_TYPE_LOCATION,
)
return START_NOT_STICKY
}Schedule periodic sync with KEEP policy
fun scheduleSync(workManager: WorkManager) {
val request = PeriodicWorkRequestBuilder<SyncWorker>(1, TimeUnit.HOURS)
.setConstraints(
Constraints.Builder()
.setRequiredNetworkType(NetworkType.CONNECTED)
.setRequiresBatteryNotLow(true)
.build()
)
.setBackoffCriteria(BackoffPolicy.EXPONENTIAL, 30, TimeUnit.SECONDS)
.build()
workManager.enqueueUniquePeriodicWork(
SyncWorker.UNIQUE_NAME, ExistingPeriodicWorkPolicy.KEEP, request,
)
}BroadcastReceiver with goAsync and timeout
// clearLocaleCache is your own suspend function
override fun onReceive(context: Context, intent: Intent) {
if (intent.action != Intent.ACTION_LOCALE_CHANGED) return
val pendingResult = goAsync()
CoroutineScope(SupervisorJob() + Dispatchers.IO).launch {
try {
withTimeout(9_000) { clearLocaleCache(context.applicationContext) }
} finally {
pendingResult.finish()
}
}
}Rules of thumb
- Prefer WorkManager over alarms for periodic sync; alarms do not retry, survive reboot, or respect network conditions.
- Never call
startForeground()after async work; call it first with a simple notification and update it later. - Prefer
ExistingPeriodicWorkPolicy.KEEPat app launch; useUPDATEonly when you change constraints or interval in a new release. - Never pass payloads larger than 10 KB in
Data; store the payload in Room or a file and pass its id or URI. - Prefer
FLAG_IMMUTABLEfor everyPendingIntent; switch toFLAG_MUTABLEonly forRemoteInputreplies or bubbles. - Never swallow
CancellationExceptionin aCoroutineWorker; it signals that constraints stopped being met or the work was cancelled.
Gotchas
- Restarting unique work on every launch with REPLACE or CANCEL_AND_REENQUEUE. Each call cancels the currently running work, so a sync that is mid-flight is killed and restarted every time the app opens. Use
KEEPfor startup scheduling andUPDATEonly when settings change. - Calling startForeground() after a network call or inside a delayed coroutine. The 5-second window starts at
startForegroundService(), so a late call triggers an ANR and a crash. CallstartForeground()first with a placeholder notification and update it later. - Omitting FOREGROUND_SERVICE_<TYPE> permission or the manifest type on target 34.
startForeground()throwsMissingForegroundServiceTypeException(orSecurityExceptionfor a missing runtime prerequisite). Add both the type permission and theforegroundServiceTypeattribute. - Forgetting unregisterReceiver() in the matching lifecycle callback. The receiver and the Activity it references leak, and the system logs a "leaked IntentReceiver" error. Pair
registerReceiver()inonStart/onResumewithunregisterReceiver()inonStop/onPause. - Using ELAPSED_REALTIME_WAKEUP for a wall-clock reminder like "at 09:00".
ELAPSED_REALTIMEis unaffected by clock or timezone changes, so the alarm fires at the wrong wall-clock time. UseRTC_WAKEUPcomputed withjava.timein the user's zone and reschedule onACTION_TIMEZONE_CHANGED. - Posting a notification on API 26+ without creating the channel first. The notification is silently dropped and only a logcat warning ("No Channel found") appears. Create channels in
Application.onCreate()or an initializer; repeated calls with the same id are safe.
Quick interview answers
When should you use WorkManager instead of a foreground service?
Use WorkManager for deferrable work that must eventually finish but does not need to run right now, such as periodic sync. Use a foreground service for long, user-visible work that must start immediately, like media playback or live navigation.
What happens if you call startForeground() after a network call in a foreground service?
The 5-second window starts at startForegroundService(), not at onStartCommand return, so a late startForeground() call causes an ANR and the system kills the process. Call startForeground() first with a simple notification and update it after the network call completes.
How do you handle exact alarms on Android 14+?
SCHEDULE_EXACT_ALARM is denied by default for most new installs targeting 33+, so check canScheduleExactAlarms() before calling setExact(). If access is missing, fall back to setAndAllowWhileIdle() and offer the user Settings.ACTION_REQUEST_SCHEDULE_EXACT_ALARM.
What is the 10 KB limit in WorkManager and how do you work around it?
Each Data input and output is capped at 10 KB; building a larger Data throws. Store the payload in Room or a file and pass only its id or URI through Data.
Why does @HiltWorker fail at runtime without extra configuration?
Without Configuration.Provider supplying a HiltWorkerFactory and without removing the default WorkManagerInitializer from the manifest, WorkManager cannot construct the worker and every run fails. Add androidx.hilt:hilt-work, the KSP compiler, and the Configuration.Provider implementation in your Application.
What is the difference between RTC_WAKEUP and ELAPSED_REALTIME_WAKEUP?
RTC_WAKEUP fires at a wall-clock time and is affected by clock and timezone changes, so use it for user-facing reminders like "at 09:00". ELAPSED_REALTIME_WAKEUP fires after a fixed delay from boot and is unaffected by clock changes, making it suitable for relative delays like "in 20 minutes".