Foreground services

Learn how to implement Android foreground services, including type declarations for Android 14, Android 15 limits, and handling background restrictions. About 25 minutes.

Why it matters

  • A foreground service keeps your process at a high priority while it does work the user is aware of: playback, navigation, a workout being tracked, a call. WorkManager is for deferrable work and limits each run to about 10 minutes.
  • The rules changed in almost every release: Android 12 (target 31) blocks most starts from the background, Android 14 (target 34) requires a service type plus a matching permission, and Android 15 puts time limits on dataSync and mediaProcessing.
  • Interviewers probe the 5-second startForeground rule, the type and permission checks, and when a foreground service is the wrong tool.
  • Most foreground-service crashes in production come from a handful of exceptions (ForegroundServiceStartNotAllowedException, ForegroundServiceDidNotStartInTimeException, MissingForegroundServiceTypeException, SecurityException). Knowing which rule throws which saves hours.

The simple explanation

  • A foreground service is a taxi with the roof light on: the user can see it is working, so the system leaves it alone.
  • The light is the notification. The licence on the dashboard is the service type and its permission (Android 14+).
  • A taxi cannot start a shift from a back alley (background start restriction, Android 12+); it has to start from the rank where the user can see it.

A foreground service is a Service that calls startForeground(id, notification, type) after it is started. Its process is treated like a visible app, and its notification appears in the shade and in the Task Manager.

Starting it. Call ContextCompat.startForegroundService(context, intent). The service must then call startForeground() within about 5 seconds, or the system raises an ANR and, from Android 12, crashes the app with ForegroundServiceDidNotStartInTimeException. Use ServiceCompat.startForeground(service, id, notification, type): it passes the type on Android 10+ and ignores it on older versions.

Background start restriction (target 31, Android 12+). Starting a foreground service while the app is in the background throws ForegroundServiceStartNotAllowedException, unless an exemption applies. Exemptions include: the app has a visible activity, the user tapped your notification, widget or other UI, a high-priority FCM message, an exact alarm firing for a user-requested action, BOOT_COMPLETED, and the user disabling battery optimisation for the app.

Types and permissions (target 34, Android 14+).

  • Declare android:foregroundServiceType on the <service>; without it, startForeground() throws MissingForegroundServiceTypeException.
  • Declare FOREGROUND_SERVICE (needed since Android 9) and the matching FOREGROUND_SERVICE_<TYPE> permission, such as FOREGROUND_SERVICE_LOCATION; a missing one throws SecurityException.
  • Some types also need a runtime prerequisite: location needs a granted location permission, camera the camera permission, microphone RECORD_AUDIO.
  • The type passed to startForeground() must be one of the types in the manifest.
  • shortService needs no extra permission but must finish within about 3 minutes.

Time limits (target 35, Android 15+). dataSync and mediaProcessing services may run for 6 hours in a 24-hour period. At the limit the system calls Service.onTimeout(startId, fgsType), and the service has a few seconds to call stopSelf() before the app crashes. The timer resets when the user brings the app to the foreground.

The notification. It needs a channel (Android 8+). From Android 13 the user can dismiss a foreground-service notification and the service keeps running. From Android 14, setOngoing(true) no longer stops most notifications from being dismissed. If POST_NOTIFICATIONS is denied (Android 13+), the service still runs, but its notification shows only in the Task Manager.

Version (target)Key rule
8 (26)startForegroundService() plus startForeground() within about 5 s; notification needs a channel
9 (28)FOREGROUND_SERVICE permission required
12 (31)Starting from the background throws ForegroundServiceStartNotAllowedException unless exempt
13 (33)The user can dismiss the notification; POST_NOTIFICATIONS is a runtime permission
14 (34)Service type in the manifest plus a matching FOREGROUND_SERVICE_* permission
15 (35)dataSync and mediaProcessing limited to 6 h per 24 h; onTimeout()

When to choose it. Use a foreground service for long work the user started and can see, which must run now (playback, navigation, an active workout, a call). Deferrable work that must finish goes to WorkManager, short urgent work to expedited WorkManager work, and work at an exact clock time to an alarm.

Notes

  • The 5-second window starts when you call startForegroundService(), not when onStartCommand returns. Call startForeground() first, with a simple notification, and update it later.
  • Use ServiceCompat.startForeground() and ServiceCompat.stopForeground(service, STOP_FOREGROUND_REMOVE); the framework stopForeground(Boolean) is deprecated since Android 13.
  • From Android 12 a start from the background throws ForegroundServiceStartNotAllowedException (a subclass of IllegalStateException), not SecurityException. Start the service from a user action while your UI is visible.
  • On target 34, a missing type in the manifest throws MissingForegroundServiceTypeException; a missing FOREGROUND_SERVICE_<TYPE> permission or a missing runtime prerequisite (for example location) throws SecurityException.
  • Types such as location, camera and microphone that rely on "while in use" permissions generally cannot be started from the background, even with an exemption.
  • From Android 13 the user can swipe the notification away and the service keeps running; from Android 14 setOngoing(true) no longer prevents that. Do not tie the service's life to the notification.
  • On Android 15 (target 35), dataSync and mediaProcessing get 6 hours per 24 hours. Override onTimeout(startId, fgsType) and call stopSelf() within a few seconds. Android 15 also blocks starting dataSync, camera, mediaPlayback, phoneCall, mediaProjection and microphone services from a BOOT_COMPLETED receiver.
  • START_STICKY asks the system to recreate the service with a null intent after it kills the process; START_NOT_STICKY does not; START_REDELIVER_INTENT redelivers the last intent. Handle the null intent and do not repeat non-idempotent work.
  • A foreground service does not survive a reboot or force-stop. For work that must resume, persist the state and decide on the next app start, or use WorkManager.
  • Calling startService() from the background without promoting to the foreground throws IllegalStateException since Android 8 (target 26).

Code example

A location-tracking service for a workout app, started from a button while the activity is visible. It promotes itself with ServiceCompat.startForeground() and the location type, offers a Stop action and cleans up its coroutines.

// TrackingService.kt
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.app.Service
import android.content.Context
import android.content.Intent
import android.content.pm.ServiceInfo
import android.os.IBinder
import androidx.core.app.NotificationCompat
import androidx.core.app.ServiceCompat
import androidx.core.content.ContextCompat
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.cancel
import kotlinx.coroutines.launch
 
class TrackingService : Service() {
 
    private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default)
    private var trackingJob: Job? = null
 
    override fun onCreate() {
        super.onCreate()
        // Idempotent; minSdk 26+ assumed
        val channel = NotificationChannel(CHANNEL_ID, "Workout tracking", NotificationManager.IMPORTANCE_LOW)
        getSystemService(NotificationManager::class.java).createNotificationChannel(channel)
    }
 
    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
        }
 
        // First thing: promote within ~5 s of startForegroundService().
        // Throws SecurityException on target 34 if location permission is not granted.
        ServiceCompat.startForeground(
            this,
            NOTIFICATION_ID,
            buildNotification(),
            ServiceInfo.FOREGROUND_SERVICE_TYPE_LOCATION, // ignored below Android 10
        )
 
        if (trackingJob == null) {
            trackingJob = scope.launch {
                // collect location updates and save them to Room
            }
        }
        // A run interrupted by the system should not restart without the user
        return START_NOT_STICKY
    }
 
    override fun onDestroy() {
        scope.cancel()
        super.onDestroy()
    }
 
    override fun onBind(intent: Intent?): IBinder? = null
 
    private fun buildNotification(): Notification {
        val stopIntent = PendingIntent.getService(
            this, 0,
            Intent(this, TrackingService::class.java).setAction(ACTION_STOP),
            PendingIntent.FLAG_IMMUTABLE,
        )
        return NotificationCompat.Builder(this, CHANNEL_ID)
            .setSmallIcon(R.drawable.ic_run)
            .setContentTitle("Tracking your run")
            .setOngoing(true) // the user can still dismiss it on Android 14+
            .setForegroundServiceBehavior(NotificationCompat.FOREGROUND_SERVICE_IMMEDIATE)
            .addAction(R.drawable.ic_stop, "Stop", stopIntent)
            .build()
    }
 
    companion object {
        private const val CHANNEL_ID = "tracking"
        private const val NOTIFICATION_ID = 1001
        private const val ACTION_STOP = "com.example.action.STOP_TRACKING"
 
        // Call from a click handler while the activity is visible
        fun start(context: Context) {
            ContextCompat.startForegroundService(context, Intent(context, TrackingService::class.java))
        }
    }
}
<!-- AndroidManifest.xml -->
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
 
<application>
    <service
        android:name=".TrackingService"
        android:exported="false"
        android:foregroundServiceType="location" />
</application>
  • ServiceInfo lives in android.content.pm. ServiceCompat.startForeground() passes the type on Android 10+ and calls the two-argument version on older devices, so no version check is needed.
  • startForeground() is the first call in onStartCommand, before any suspend work, so the 5-second window cannot be missed.
  • On target 34 the manifest type, FOREGROUND_SERVICE_LOCATION and a granted ACCESS_FINE_LOCATION (or coarse) must all be in place, or startForeground() throws.
  • start() is called from a button click, so the app is in the foreground and the Android 12 background-start restriction does not apply.
  • FOREGROUND_SERVICE_IMMEDIATE shows the notification right away; otherwise Android 12+ may delay it by up to 10 seconds for some services.

Run the idea in plain Kotlin

A model of the checks the system runs when an app starts a foreground service, in the order they happen: the background-start check, the 5-second window, and the Android 14 type and permission checks. The names match the real exceptions; the logic is simplified.

data class AppManifest(val types: Set<String>, val permissions: Set<String>)

val typePermission: Map<String, String?> = mapOf(
  "location" to "FOREGROUND_SERVICE_LOCATION",
  "mediaPlayback" to "FOREGROUND_SERVICE_MEDIA_PLAYBACK",
  "dataSync" to "FOREGROUND_SERVICE_DATA_SYNC",
  "shortService" to null // no extra permission
)

fun startFgs(
  targetSdk: Int,
  appVisible: Boolean,
  exempt: Boolean,
  manifest: AppManifest,
  type: String,
  secondsToStartForeground: Int
): String {
  if (targetSdk >= 31 && !appVisible && !exempt) return "ForegroundServiceStartNotAllowedException"
  if (secondsToStartForeground > 5) return "ANR + ForegroundServiceDidNotStartInTimeException"
  if (targetSdk >= 28 && "FOREGROUND_SERVICE" !in manifest.permissions) return "SecurityException: FOREGROUND_SERVICE"
  if (targetSdk >= 34) {
      if (manifest.types.isEmpty()) return "MissingForegroundServiceTypeException"
      if (type !in manifest.types) return "IllegalArgumentException: type not in manifest"
      val perm = typePermission[type]
      if (perm != null && perm !in manifest.permissions) return "SecurityException: " + perm
  }
  return "running as " + type
}

fun main() {
  val good = AppManifest(setOf("location"), setOf("FOREGROUND_SERVICE", "FOREGROUND_SERVICE_LOCATION"))
  val noTypePerm = AppManifest(setOf("location"), setOf("FOREGROUND_SERVICE"))
  val noType = AppManifest(emptySet(), setOf("FOREGROUND_SERVICE"))

  println("1 visible, target 34:       " + startFgs(34, true, false, good, "location", 0))
  println("2 background, target 34:    " + startFgs(34, false, false, good, "location", 0))
  println("3 background, exempt:       " + startFgs(34, false, true, good, "location", 0))
  println("4 slow startForeground:     " + startFgs(34, true, false, good, "location", 7))
  println("5 missing type permission:  " + startFgs(34, true, false, noTypePerm, "location", 0))
  println("6 no type in manifest:      " + startFgs(34, true, false, noType, "location", 0))
  println("7 same app, target 33:      " + startFgs(33, true, false, noType, "location", 0))

  val usedMinutes = 360
  val limitMinutes = 6 * 60
  println("8 dataSync on Android 15 after " + usedMinutes + " min: " +
      if (usedMinutes >= limitMinutes) "onTimeout() -> call stopSelf()" else "still allowed")
}

Expected output:

1 visible, target 34:       running as location
2 background, target 34:    ForegroundServiceStartNotAllowedException
3 background, exempt:       running as location
4 slow startForeground:     ANR + ForegroundServiceDidNotStartInTimeException
5 missing type permission:  SecurityException: FOREGROUND_SERVICE_LOCATION
6 no type in manifest:      MissingForegroundServiceTypeException
7 same app, target 33:      running as location
8 dataSync on Android 15 after 360 min: onTimeout() -> call stopSelf()

In production

Crash spike after raising targetSdk to 34
  • A podcast app raised targetSdk to 34. Crash reports filled with SecurityException: Starting FGS with type mediaPlayback ... requires permissions: FOREGROUND_SERVICE_MEDIA_PLAYBACK from devices on Android 14 and later.
  • The manifest declared FOREGROUND_SERVICE and android:foregroundServiceType="mediaPlayback", but not the new type permission, and nobody had tested playback on an Android 14 device after the change.
  • On Android 13 and lower the same build worked, so the bug only appeared as users updated their phones.
The fix
  • They added <uses-permission android:name="android.permission.FOREGROUND_SERVICE_MEDIA_PLAYBACK" /> and switched to ServiceCompat.startForeground(this, id, notification, ServiceInfo.FOREGROUND_SERVICE_TYPE_MEDIA_PLAYBACK).
  • They added a checklist item for every targetSdk bump: read the behaviour changes page, then run each foreground-service path on a device with the new version.
  • They added an instrumented test on an API 34 emulator that starts playback and asserts the service is in the foreground.
Sync service crashed when started from a push message
  • A messaging app started a foreground service from a normal-priority FCM message to download attachments.
  • On Android 12+ devices with the app in the background, startForegroundService() threw ForegroundServiceStartNotAllowedException. The call was inside a broad try/catch, so the downloads silently never happened.
  • On their test devices the app was usually open, so nobody noticed.
The fix
  • They reproduced it by sending the app to the background and sending a test push; logcat showed the exception.
  • They moved attachment downloads to WorkManager: an expedited OneTimeWorkRequest with NetworkType.CONNECTED, enqueued from the FCM service. Expedited work can run from the background within the app's quota.
  • They removed the catch-all and logged the exception to crash reporting, so a similar regression would be visible.

Common mistakes

  • Calling startForeground after async work. The 5-second window starts at startForegroundService(). Calling startForeground() after a network call or inside a delayed coroutine causes an ANR and a crash. Call it first and update the notification later.
  • Forgetting the type permission on target 34. FOREGROUND_SERVICE alone is not enough; add the matching FOREGROUND_SERVICE_<TYPE> permission and declare the type in the manifest, or startForeground() throws.
  • Starting a foreground service from the background. From Android 12 this throws ForegroundServiceStartNotAllowedException unless an exemption applies. Start it from a user action, or use expedited WorkManager work.
  • Relying on setOngoing(true) to keep the notification. From Android 13 the user can dismiss foreground-service notifications, and from Android 14 setOngoing(true) no longer prevents it. The service keeps running; do not treat a dismissed notification as "stop".
  • Ignoring the Android 15 time limit. A dataSync service that runs for more than 6 hours in a day gets onTimeout() and crashes the app if it does not stop. Split long transfers into WorkManager work or stop in onTimeout().
  • Not cancelling coroutines in onDestroy. A CoroutineScope created in the service keeps running after stopSelf() unless you cancel it, which leaks the service and its work.
  • Using START_STICKY for non-idempotent work. The service is recreated with a null intent. Use START_NOT_STICKY, or persist progress and check it before repeating work.

Interview questions

Answer out loud first. Then reveal the answer and compare it at each depth.

“What happens if a service started with startForegroundService() does not call startForeground() in time?”

“What changed for foreground services in Android 14 and 15?”

“When would you choose a foreground service over WorkManager?”

“What are the background start restrictions, and how do you handle them?”

Quiz

An app targeting SDK 34 declares FOREGROUND_SERVICE and android:foregroundServiceType="mediaPlayback" on its service. What else does it need before startForeground() succeeds with that type?

A service is started with startForegroundService() but calls startForeground() only after an 8-second network call. What happens?

On Android 14, a user swipes away your foreground service's notification, which was built with setOngoing(true). What happens?

An app targeting SDK 31 calls startForegroundService() from the background with no exemption. What happens?

0 of 4 answered

Mini task

Add a foreground service to your app (15 min)

  1. Create a Service subclass called LocationTrackingService. In onCreate, create a notification channel "location_tracking" with IMPORTANCE_LOW.

  2. In AndroidManifest.xml, add the <service> with android:exported="false" and android:foregroundServiceType="location", and the permissions FOREGROUND_SERVICE, FOREGROUND_SERVICE_LOCATION, ACCESS_FINE_LOCATION and POST_NOTIFICATIONS.

  3. In onStartCommand, call ServiceCompat.startForeground(this, 1, notification, ServiceInfo.FOREGROUND_SERVICE_TYPE_LOCATION) as the first statement. Build the notification with NotificationCompat.Builder, a small icon and a Stop action whose PendingIntent uses FLAG_IMMUTABLE. Return START_NOT_STICKY.

  4. Add a Start button in your activity that requests location permission and then calls ContextCompat.startForegroundService(). Make the Stop action call ServiceCompat.stopForeground(this, ServiceCompat.STOP_FOREGROUND_REMOVE) and stopSelf().

  5. On an Android 14+ device or emulator, start the service and check that the notification appears. Swipe it away and confirm the service is still listed in the Task Manager (the active apps button in quick settings).

  6. Break it on purpose: remove FOREGROUND_SERVICE_LOCATION, run again and read the SecurityException in logcat. Then put it back, deny the location permission, and see the same exception. Put everything back.

Done when: the service starts from the button with its notification, stops from the Stop action, and you have seen both failure modes in logcat.

Next: Notifications and channels