In kotlin what is the difference between work manager , alarm manager , background services ?

Answer

Overview

Android provides three main background processing mechanisms — WorkManager, AlarmManager, and Background Services — each suited for different use cases.


Background Services

A Service is a component that runs code in the background without a UI. However, since Android 8.0 (Oreo), plain background services are heavily restricted.

kotlin
// Foreground Service — stays alive, shows a notification
class DownloadService : Service() {
    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        // Required for Android 8+ — must show notification
        startForeground(1, buildNotification())
        // Do background work
        return START_STICKY
    }
    override fun onBind(intent: Intent?) = null
}
TypeDescription
Foreground ServiceVisible to user (notification), not killed by OS
Background ServiceAndroid 8+ kills these when app is not in foreground
Bound ServiceLives while component is bound to it

AlarmManager

AlarmManager schedules tasks to run at a specific time, even when the app is not running. It wakes up the device.

kotlin
val alarmManager = getSystemService(Context.ALARM_SERVICE) as AlarmManager
val intent = Intent(this, AlarmReceiver::class.java)
val pendingIntent = PendingIntent.getBroadcast(
    this, 0, intent,
    PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
)

// Schedule exact alarm at 9:00 AM
alarmManager.setExactAndAllowWhileIdle(
    AlarmManager.RTC_WAKEUP,
    System.currentTimeMillis() + 60_000, // 1 minute from now
    pendingIntent
)
kotlin
// Receiving the alarm
class AlarmReceiver : BroadcastReceiver() {
    override fun onReceive(context: Context, intent: Intent) {
        // Runs at the scheduled time — even if app is closed
        showNotification(context)
    }
}

WorkManager

WorkManager is the recommended solution for deferrable, guaranteed background work. It works with Doze mode, device restarts, and app process death.

kotlin
// Define the work
class SyncWorker(context: Context, params: WorkerParameters) : CoroutineWorker(context, params) {
    override suspend fun doWork(): Result {
        return try {
            syncDataWithServer()
            Result.success()
        } catch (e: Exception) {
            Result.retry()
        }
    }
}

// Schedule the work
val syncRequest = PeriodicWorkRequestBuilder<SyncWorker>(15, TimeUnit.MINUTES)
    .setConstraints(
        Constraints.Builder()
            .setRequiredNetworkType(NetworkType.CONNECTED)
            .setRequiresBatteryNotLow(true)
            .build()
    )
    .build()

WorkManager.getInstance(context).enqueueUniquePeriodicWork(
    "data_sync",
    ExistingPeriodicWorkPolicy.KEEP,
    syncRequest
)

Key Differences

FeatureWorkManagerAlarmManagerBackground Service
Survives device restart✅ Yes✅ Yes (with BOOT_COMPLETED)❌ No
Works in Doze mode✅ Yes⚠️ Only with
text
setExactAndAllowWhileIdle
❌ Killed
Exact timing❌ Not guaranteed✅ Exact to the millisecond❌ No
Constraints✅ Network, battery, charging❌ No❌ No
Use casePeriodic sync, uploadsReminders, exact alarmsLong-running active work
Android versionAll (via Jetpack)AllRestricted 8+
Battery efficient✅ Batches work❌ Can drain battery❌ Poor

When to Use Which

Use CaseBest Choice
Daily news sync
text
WorkManager
Upload photos when on Wi-Fi
text
WorkManager
with NetworkType constraint
Medicine reminder at exact 8:00 AM
text
AlarmManager
Music player playing continuously
text
Foreground Service
File download in background
text
Foreground Service
Retry failed API call
text
WorkManager
with retry policy

Google Recommendation: Use

text
WorkManager
for almost all background tasks. Use
text
AlarmManager
only when exact timing is critical (alarms, reminders). Use
text
Foreground Service
for user-visible long-running operations.