Android Foreground Notification — Complete Guide
In this tutorial, you'll learn about Android Foreground Notification. We cover key concepts, practical examples, and best practices to help you understand and apply this topic effectively.
The Problem
Your foreground service crashes with ForegroundServiceStartNotAllowedException on Android 12+ or the notification doesn't appear within 5 seconds.
Wrong Approach ❌
// Starting foreground service without notification ready
class MyService : Service() {
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
// startForeground called AFTER some work — too late!
Thread {
doWork()
startForeground(NOTIFICATION_ID, buildNotification()) // CRASH!
}.start()
return START_STICKY
}
}
Output: ForegroundServiceStartNotAllowedException on API 31+. Service killed.
Right Approach ✅
class DataSyncService : Service() {
override fun onCreate() {
super.onCreate()
createNotificationChannel()
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
val notification = buildNotification("Starting sync...")
startForeground(NOTIFICATION_ID, notification) // MUST be immediate
// Now do the work
CoroutineScope(Dispatchers.IO).launch {
try {
syncData()
updateNotification("Sync complete")
stopSelf()
} catch (e: Exception) {
updateNotification("Sync failed")
stopSelf()
}
}
return START_NOT_STICKY
}
private fun buildNotification(content: String): Notification {
return NotificationCompat.Builder(this, SYNC_CHANNEL_ID)
.setContentTitle("Data Sync")
.setContentText(content)
.setSmallIcon(R.drawable.ic_sync)
.setOngoing(true)
.setProgress(0, 0, true) // Indeterminate progress
.setForegroundServiceBehavior(ForegroundServiceBehavior.IMMEDIATE_DISPLAY) // API 34+
.build()
}
private fun updateNotification(content: String) {
val notification = buildNotification(content)
val manager = NotificationManagerCompat.from(this)
manager.notify(NOTIFICATION_ID, notification)
}
// For Android 12+ geolocation services
class LocationService : Service() {
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
val notification = NotificationCompat.Builder(this, LOCATION_CHANNEL_ID)
.setContentTitle("Using your location")
.setContentText("App is accessing location in the background")
.setSmallIcon(R.drawable.ic_location)
.setOngoing(true)
.build()
startForeground(NOTIFICATION_ID, notification)
return START_STICKY
}
}
override fun onBind(intent: Intent?) = null
override fun onDestroy() {
super.onDestroy()
// Clean up resources
}
}
Output: Foreground service starts reliably with visible notification.
Prevention
- Call
startForeground()immediately inonStartCommand()— within 5 seconds. - Use
START_NOT_STICKYto avoid automatic restarts. - Set
setOngoing(true)for non-dismissible notifications. - For Android 12+, check
Intent.ACTION_FOREGROUND_SERVICE_STARTrestrictions.
Common Mistakes with notification foreground
- Forgetting
deriving (Show, Eq)on custom data types needed for debugging - Placing the wildcard pattern first in case expressions, making all subsequent patterns unreachable
- Using
headandtailinstead of pattern matching, causing runtime errors on empty lists
These mistakes appear frequently in real-world Android code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro