Foreground services
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
dataSyncandmediaProcessing. - Interviewers probe the 5-second
startForegroundrule, 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:foregroundServiceTypeon the<service>; without it,startForeground()throwsMissingForegroundServiceTypeException. - Declare
FOREGROUND_SERVICE(needed since Android 9) and the matchingFOREGROUND_SERVICE_<TYPE>permission, such asFOREGROUND_SERVICE_LOCATION; a missing one throwsSecurityException. - Some types also need a runtime prerequisite:
locationneeds a granted location permission,camerathe camera permission,microphoneRECORD_AUDIO. - The type passed to
startForeground()must be one of the types in the manifest. shortServiceneeds 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 whenonStartCommandreturns. CallstartForeground()first, with a simple notification, and update it later. - Use
ServiceCompat.startForeground()andServiceCompat.stopForeground(service, STOP_FOREGROUND_REMOVE); the frameworkstopForeground(Boolean)is deprecated since Android 13. - From Android 12 a start from the background throws
ForegroundServiceStartNotAllowedException(a subclass ofIllegalStateException), notSecurityException. Start the service from a user action while your UI is visible. - On target 34, a missing type in the manifest throws
MissingForegroundServiceTypeException; a missingFOREGROUND_SERVICE_<TYPE>permission or a missing runtime prerequisite (for example location) throwsSecurityException. - Types such as
location,cameraandmicrophonethat 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),
dataSyncandmediaProcessingget 6 hours per 24 hours. OverrideonTimeout(startId, fgsType)and callstopSelf()within a few seconds. Android 15 also blocks startingdataSync,camera,mediaPlayback,phoneCall,mediaProjectionandmicrophoneservices from aBOOT_COMPLETEDreceiver. START_STICKYasks the system to recreate the service with anullintent after it kills the process;START_NOT_STICKYdoes not;START_REDELIVER_INTENTredelivers the last intent. Handle thenullintent 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 throwsIllegalStateExceptionsince 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>ServiceInfolives inandroid.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 inonStartCommand, before any suspend work, so the 5-second window cannot be missed.- On target 34 the manifest type,
FOREGROUND_SERVICE_LOCATIONand a grantedACCESS_FINE_LOCATION(or coarse) must all be in place, orstartForeground()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_IMMEDIATEshows 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
- A podcast app raised
targetSdkto 34. Crash reports filled withSecurityException: Starting FGS with type mediaPlayback ... requires permissions: FOREGROUND_SERVICE_MEDIA_PLAYBACKfrom devices on Android 14 and later. - The manifest declared
FOREGROUND_SERVICEandandroid: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.
- They added
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_MEDIA_PLAYBACK" />and switched toServiceCompat.startForeground(this, id, notification, ServiceInfo.FOREGROUND_SERVICE_TYPE_MEDIA_PLAYBACK). - They added a checklist item for every
targetSdkbump: 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.
- 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()threwForegroundServiceStartNotAllowedException. The call was inside a broadtry/catch, so the downloads silently never happened. - On their test devices the app was usually open, so nobody noticed.
- 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
OneTimeWorkRequestwithNetworkType.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(). CallingstartForeground()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_SERVICEalone is not enough; add the matchingFOREGROUND_SERVICE_<TYPE>permission and declare the type in the manifest, orstartForeground()throws. - Starting a foreground service from the background. From Android 12 this throws
ForegroundServiceStartNotAllowedExceptionunless 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
dataSyncservice that runs for more than 6 hours in a day getsonTimeout()and crashes the app if it does not stop. Split long transfers into WorkManager work or stop inonTimeout(). - Not cancelling coroutines in onDestroy. A
CoroutineScopecreated in the service keeps running afterstopSelf()unless you cancel it, which leaks the service and its work. - Using START_STICKY for non-idempotent work. The service is recreated with a
nullintent. UseSTART_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)
-
Create a
Servicesubclass calledLocationTrackingService. InonCreate, create a notification channel"location_tracking"withIMPORTANCE_LOW. -
In
AndroidManifest.xml, add the<service>withandroid:exported="false"andandroid:foregroundServiceType="location", and the permissionsFOREGROUND_SERVICE,FOREGROUND_SERVICE_LOCATION,ACCESS_FINE_LOCATIONandPOST_NOTIFICATIONS. -
In
onStartCommand, callServiceCompat.startForeground(this, 1, notification, ServiceInfo.FOREGROUND_SERVICE_TYPE_LOCATION)as the first statement. Build the notification withNotificationCompat.Builder, a small icon and a Stop action whosePendingIntentusesFLAG_IMMUTABLE. ReturnSTART_NOT_STICKY. -
Add a Start button in your activity that requests location permission and then calls
ContextCompat.startForegroundService(). Make the Stop action callServiceCompat.stopForeground(this, ServiceCompat.STOP_FOREGROUND_REMOVE)andstopSelf(). -
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).
-
Break it on purpose: remove
FOREGROUND_SERVICE_LOCATION, run again and read theSecurityExceptionin 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.