Android Services and Background Tasks Explained - Complete Guide
In this tutorial, you'll learn how to run background work in Android using Services, WorkManager, and modern Jetpack APIs with practical Kotlin examples.
What You'll Learn
how to run background work in Android using Services, WorkManager, and modern Jetpack APIs with practical Kotlin examples — Background work powers music playback, file downloads, location tracking, and data sync. Mishandling it drains battery and can trigger Play Store restrictions.
Why It Matters
Background work powers music playback, file downloads, location tracking, and data sync. Mishandling it drains battery and can trigger Play Store restrictions.
Real-World Use
A music player runs a foreground service for playback (persistent notification), uses WorkManager to sync playlists, and uses JobScheduler to download episodes only on WiFi while charging.
Learning Path
flowchart LR
[Activity Lifecycle] --> [Services & Background Tasks] --> [WorkManager] --> [Notifications]
style 2 fill:#4CAF50,color:#fff
Foreground Service for Music Playback
class MusicPlayerService : Service() {
private lateinit var mediaPlayer: MediaPlayer
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
val notification = createNotification()
startForeground(NOTIFICATION_ID, notification)
return START_STICKY
}
private fun createNotification(): Notification {
val channelId = "music_player_channel"
val channel = NotificationChannel(channelId, "Music Player", NotificationManager.IMPORTANCE_LOW)
val manager = getSystemService(NotificationManager::class.java)
manager.createNotificationChannel(channel)
return NotificationCompat.Builder(this, channelId)
.setContentTitle("Now Playing").setContentText("Song - Artist")
.setSmallIcon(android.R.drawable.ic_media_play).setOngoing(true).build()
}
}
Expected output: A foreground service with a persistent notification keeps the app alive during music playback.
WorkManager for Deferrable Sync
class SyncWorker(context: Context, params: WorkerParameters) : CoroutineWorker(context, params) {
override suspend fun doWork(): Result {
return try {
val data = RetrofitClient.apiService.getLatestData()
val db = AppDatabase.getInstance(applicationContext)
db.dataDao().insertAll(data)
Result.success()
} catch (e: Exception) {
if (runAttemptCount < 3) Result.retry() else Result.failure()
}
}
}
val syncRequest = OneTimeWorkRequestBuilder<SyncWorker>()
.setConstraints(Constraints.Builder().setRequiredNetworkType(NetworkType.CONNECTED).build())
.setBackoffCriteria(BackoffPolicy.EXPONENTIAL, 1, TimeUnit.MINUTES)
.build()
WorkManager.getInstance(context).enqueue(syncRequest)
Expected output: WorkManager schedules the sync worker to run when network is available, with exponential backoff on failure.
Periodic WorkManager
val periodicSync = PeriodicWorkRequestBuilder<SyncWorker>(15, TimeUnit.MINUTES)
.setConstraints(Constraints.Builder().setRequiredNetworkType(NetworkType.CONNECTED).build())
.build()
WorkManager.getInstance(context).enqueueUniquePeriodicWork(
"periodic_sync", ExistingPeriodicWorkPolicy.KEEP, periodicSync
)
Expected output: WorkManager runs sync every 15 minutes when network is available, using unique work to prevent duplicates.
Common Errors
- Background service killed by system - foreground services need a visible notification within 5 seconds
- WorkManager worker not running - check constraints; if WiFi required and not connected, the worker waits
- FOREGROUND_SERVICE_TYPE not specified on Android 14+ - declare at least one foreground service type
- ANR from long work on main thread - services run on main thread by default; use coroutines or threads
- AlarmManager inexact timing on Android 12+ - exact alarms require SCHEDULE_EXACT_ALARM permission
Practice Questions
What is the difference between foreground and background services?
Why prefer WorkManager over a plain Service for data sync?
How does the system decide when to run a JobScheduler task?
What happens to WorkManager work if the device reboots before completion?
When should you use AlarmManager instead of WorkManager?
Challenge
Build a podcast download app: schedule weekly episode downloads with WorkManager (WiFi-only, while charging). Show a notification on completion. Handle device reboot.
Real-World Task
Implement a location-tracking foreground service for a fitness app. Use foregroundServiceType='location', request ACCESS_BACKGROUND_LOCATION permission, and periodically send location to a server.
Frequently Asked Questions
{{< faq question="What happens to a foreground service when the user swipes away the app?">}} The foreground service continues running. Swiping away removes the activity but the service and notification persist. {{< /faq >}}
{{< faq question="Can I start a background service on Android 12+?">}} Not directly from background. Use WorkManager or JobScheduler instead. {{< /faq >}}
{{< faq question="How many WorkManager workers run simultaneously?">}} The default thread pool is 2 workers. Additional workers queue until threads are available. {{< /faq >}}
Security Tip: Validate all data received from network operations in your worker before storing it. Background services are a vector for injection attacks if you blindly Process server responses.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro