Skip to content

Android Foreground Notification — Complete Guide

DodaTech Updated 2026-06-24 2 min read

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 in onStartCommand() — within 5 seconds.
  • Use START_NOT_STICKY to avoid automatic restarts.
  • Set setOngoing(true) for non-dismissible notifications.
  • For Android 12+, check Intent.ACTION_FOREGROUND_SERVICE_START restrictions.

Common Mistakes with notification foreground

  1. Forgetting deriving (Show, Eq) on custom data types needed for debugging
  2. Placing the wildcard pattern first in case expressions, making all subsequent patterns unreachable
  3. Using head and tail instead 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

### What is ForegroundServiceBehavior.IMMEDIATE_DISPLAY?

Added in API 34, it ensures the notification is displayed immediately. Without it, the system may delay showing the notification for up to 10 seconds.

### Can I remove the notification after the service stops?

Call stopForeground(REMOVE_NOTIFICATION) before stopSelf(). If you don't call this, the notification remains (use STOP_FOREGROUND_DETACH if you want the notification to persist).

### What happens if I don't call startForeground within 5 seconds?

The system throws ForegroundServiceStartNotAllowedException on Android 12+ and stops the service. On older versions, the service may run but its priority is reduced.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro