Background work cheat sheet

Revise Android background work: WorkManager, foreground services, notifications, alarms, and broadcast receivers with Kotlin and Jetpack APIs.

Key ideas

  1. Choose by guarantee: a coroutine in viewModelScope for screen-bound work, WorkManager for deferrable work, a foreground service for long user-visible work, an alarm for an exact time.
  2. 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.
  3. Call startForeground() within 5 seconds of startForegroundService(); the window starts at the call, not at onStartCommand return.
  4. On target 34 a missing foregroundServiceType in the manifest throws MissingForegroundServiceTypeException; add the matching FOREGROUND_SERVICE_<TYPE> permission too.
  5. @HiltWorker needs HiltWorkerFactory wired through Configuration.Provider and the default WorkManagerInitializer removed from the manifest, or every run fails at runtime.
  6. Create NotificationChannel objects at app start; the id is a permanent key for the user's settings and cannot be reset by code.
  7. Exact alarms require SCHEDULE_EXACT_ALARM access; on Android 14 it is denied by default for most new installs, so check canScheduleExactAlarms() and fall back to inexact.
  8. onReceive() runs on the main thread; use goAsync() for a few seconds of work or hand off to WorkManager for anything longer or retryable.
  9. All alarms are cleared on reboot and force-stop; persist the schedule and reschedule on BOOT_COMPLETED with RECEIVE_BOOT_COMPLETED.
  10. Result.retry() applies the configured backoff; Result.failure() stops the work and fails any chained work; cap retries with runAttemptCount.

APIs at a glance

API or termUse it for
WorkManagerEnqueue deferrable background work with constraints, retry, and unique-name policies.
CoroutineWorkerSuspend-based worker; receives CancellationException when constraints fail or work is cancelled.
PeriodicWorkRequestBuilderSchedule recurring work; minimum interval is 15 minutes, each run gets ~10 minutes.
ExistingPeriodicWorkPolicy.KEEPNo-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).
NotificationChannelPermanent 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.
@HiltWorkerDI annotation for workers; requires HiltWorkerFactory in Configuration.Provider and removal of the default initializer.
PendingIntent.FLAG_IMMUTABLEMutability 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_EXPORTEDRequired 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.KEEP at app launch; use UPDATE only 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_IMMUTABLE for every PendingIntent; switch to FLAG_MUTABLE only for RemoteInput replies or bubbles.
  • Never swallow CancellationException in a CoroutineWorker; 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 KEEP for startup scheduling and UPDATE only 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. Call startForeground() first with a placeholder notification and update it later.
  • Omitting FOREGROUND_SERVICE_<TYPE> permission or the manifest type on target 34. startForeground() throws MissingForegroundServiceTypeException (or SecurityException for a missing runtime prerequisite). Add both the type permission and the foregroundServiceType attribute.
  • 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() in onStart/onResume with unregisterReceiver() in onStop/onPause.
  • Using ELAPSED_REALTIME_WAKEUP for a wall-clock reminder like "at 09:00". ELAPSED_REALTIME is unaffected by clock or timezone changes, so the alarm fires at the wrong wall-clock time. Use RTC_WAKEUP computed with java.time in the user's zone and reschedule on ACTION_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".

Go deeper