Skip to content
Tutorials Center
My learning

Topics

Lesson 65 of 104 ยท Coroutines and Background Work

Services, Notifications and Foreground Work

Understand Android services (started and bound), foreground service types, notification channels, the POST_NOTIFICATIONS permission, alarms versus WorkManager and background limits.

Some things an app does should keep going while the user looks at something else: playing music, tracking a run, uploading a large video. Android answers with the service, a component without a screen. Other things need to reach the user when the app is not open at all: a message arrived, a timer finished. Android answers with the notification. The two often work together, because a service that runs in the user's awareness must show a notification.

Android has also spent a decade making the background quieter, because apps that run unseen drain batteries. As a result, this area is mostly about rules: which kinds of background work are still allowed, what you must declare, and what the user can turn off. This lesson explains started and bound services, foreground services and their types, notification channels, the notification permission, alarms, and how all of it compares with WorkManager. The Android classes cannot run here, so the real code is read-only; the TryIts are stand-ins that model the rules (a service lifecycle with the foreground restrictions, and a notification manager with channel importance) in plain Kotlin.

Started and bound services

A Service is a class that the system creates and keeps alive according to who is using it. There are two ways to use one, and a service can be both.

  • A started service is begun with startService() (or startForegroundService()). It keeps running until it stops itself with stopSelf() or someone calls stopService(). Its work begins in onStartCommand().
  • A bound service is a server for clients. A component calls bindService() and receives an IBinder from onBind(), a handle for calling the service directly. The service lives while at least one client is bound and is destroyed after the last client unbinds.
flowchart TD
    A["startService()"] --> B["onCreate (once)<br/>onStartCommand"]
    C["bindService()"] --> D["onCreate (once)<br/>onBind"]
    B --> R(("running"))
    D --> R
    R -->|"stopSelf() or stopService()<br/>and no clients bound"| X["onDestroy"]
    R -->|"last client unbinds<br/>and not started"| X

A service runs while it is started or has bound clients. It is destroyed when neither is true.

Three facts surprise newcomers:

  1. A service runs on the main thread by default. It is not a background thread. Start coroutines or use WorkManager for the work itself.
  2. A service is not a separate process. It lives in your app's process (unless you ask otherwise), and the process can still be killed.
  3. onStartCommand returns a flag that tells the system what to do if the service is killed: START_NOT_STICKY (do not restart), START_STICKY (restart with a null intent) or START_REDELIVER_INTENT (restart and deliver the last intent again).
Kotlin
// read-only example: a minimal started service
class SyncService : Service() {
    private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default)

    override fun onBind(intent: Intent?): IBinder? = null      // not a bound service

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        scope.launch {
            doTheWork()
            stopSelf(startId)                                  // done: let the system destroy us
        }
        return START_NOT_STICKY
    }

    override fun onDestroy() {
        scope.cancel()
        super.onDestroy()
    }
}

Today, plain started services for background work are rarely the right answer. Since Android 8 (API 26), an app in the background cannot start a plain background service freely, and the system stops background services shortly after the app leaves the screen. If work must survive that, you use either a foreground service or WorkManager.

Foreground services

A foreground service is a service the user knows about. It is allowed to keep running when the app is in the background because it must show an ongoing notification that the user can see. Typical examples are music playback, navigation and an active workout.

Kotlin
// read-only example: starting and promoting a foreground service
val intent = Intent(context, PlayerService::class.java)
ContextCompat.startForegroundService(context, intent)

// inside PlayerService.onStartCommand
val notification = NotificationCompat.Builder(this, "playback")
    .setSmallIcon(R.drawable.ic_music)
    .setContentTitle("Now playing")
    .setOngoing(true)
    .build()

ServiceCompat.startForeground(
    this, NOTIFICATION_ID, notification,
    ServiceInfo.FOREGROUND_SERVICE_TYPE_MEDIA_PLAYBACK,
)

After startForegroundService() you have a few seconds to call startForeground(), or the system throws an exception and the app can crash. The rules have tightened with each Android release:

  • Types (Android 14 and up). Every foreground service declares at least one type in the manifest (android:foregroundServiceType) and passes it to startForeground. The types include mediaPlayback, location, camera, microphone, phoneCall, health, dataSync, connectedDevice, mediaProjection, remoteMessaging, shortService and specialUse. Each needs its own permission, such as FOREGROUND_SERVICE_MEDIA_PLAYBACK, and some types need runtime permissions too (location needs location access, camera needs the camera permission).
  • Starting from the background (Android 12 and up). An app in the background generally cannot start a foreground service. The system throws ForegroundServiceStartNotAllowedException unless a documented exemption applies, for example the app was just launched by a user action, a high-priority push message arrived or an exact alarm fired.
  • Time limits. Some types are limited: dataSync and mediaProcessing services get a few hours per day, and a shortService is meant for work of about three minutes. When the limit is reached, the system calls onTimeout() and you must stop.
  • Honest use. Store policies expect a foreground service to be tied to something the user asked for. "Keep my app alive" is not a reason.

The first stand-in encodes these rules for a pretend service. It tracks started and bound state, destroys the service when neither remains, and rejects the foreground calls that the platform rejects.

Kotlin Service lifecycle and foreground rules (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

In the third scenario the player is both started and bound, so stopSelf() leaves it running until the client unbinds. That is the rule behind the diagram: a service ends only when neither reason to run remains.

Notifications and channels

A notification is a message in the system's shade, with a title, text, an icon and an optional action when tapped. Since Android 8 every notification belongs to a notification channel, a named category with its own settings, which you create and the user controls. A chat app might have the channels "Messages", "Mentions" and "Promotions", and the user can silence only the last one.

A channel's importance decides how intrusive it is:

Importance Sound Pop-up (heads-up) Status bar icon
IMPORTANCE_HIGH Yes Yes Yes
IMPORTANCE_DEFAULT Yes No Yes
IMPORTANCE_LOW No No Yes
IMPORTANCE_MIN No No No (shade only)
IMPORTANCE_NONE Blocked Blocked Blocked
Kotlin
// read-only example: creating a channel and posting
val channel = NotificationChannel("messages", "Messages", NotificationManager.IMPORTANCE_HIGH).apply {
    description = "New chat messages"
}
context.getSystemService(NotificationManager::class.java).createNotificationChannel(channel)

val notification = NotificationCompat.Builder(context, "messages")
    .setSmallIcon(R.drawable.ic_chat)
    .setContentTitle("Ada")
    .setContentText("Lunch at 12?")
    .setContentIntent(openChatPendingIntent)            // a PendingIntent created with FLAG_IMMUTABLE
    .setAutoCancel(true)
    .build()

NotificationManagerCompat.from(context).notify(1001, notification)

Create channels once, for example at app start; creating an existing channel again is harmless. After a channel exists, you cannot raise its importance or change its sound: the system respects what the user chose, and at most lowers an unmodified channel. Plan the categories before you ship, because splitting one channel into two later forces you to choose new IDs. Posting to a channel that does not exist is silently dropped on Android 8 and later.

The notification permission

From Android 13 (API 33), apps that target API 33 or higher need the runtime permission POST_NOTIFICATIONS to show notifications. You ask for it like any other permission, see Runtime Permissions, and it is best to ask in context, right after the user does something that makes a notification valuable ("Remind me tomorrow"). If the user says no, your app still works; it just cannot post. Foreground service notifications are shown in the task manager even without the permission, but are not shown in the shade.

Kotlin
// read-only example
val launcher = rememberLauncherForActivityResult(ActivityResultContracts.RequestPermission()) { granted ->
    viewModel.onNotificationPermissionResult(granted)
}
// later, in a click handler:
if (Build.VERSION.SDK_INT >= 33) launcher.launch(Manifest.permission.POST_NOTIFICATIONS)

The second stand-in is a notification manager with channels, importance and the permission rule. It reports what the user would see for each post and shows why re-creating a channel cannot override what the user chose.

Kotlin Notification channels, importance and permission (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The output shows the three silent failures to remember: no permission means no notification, a misspelled channel means no notification, and a channel the user turned off stays off, however many times your code re-creates it.

Alarms, WorkManager and background limits

Android has several tools for "do this later", and each fits a different promise.

flowchart TD
    Q["Background work needed"] --> A{"User sees it,<br/>ongoing?"}
    A -->|"Yes: music, navigation, workout"| FS["Foreground service<br/>with notification and type"]
    A -->|"No"| B{"Needs an exact<br/>time?"}
    B -->|"Yes: alarm clock, calendar"| AL["AlarmManager exact alarm<br/>(special permission)"]
    B -->|"No"| W["WorkManager<br/>(constraints, retries)"]

Choose the foreground service for visible work, an alarm for exact times, and WorkManager for everything deferrable.

  • AlarmManager fires an intent at a time. Inexact alarms are batched to save battery. Exact alarms need the SCHEDULE_EXACT_ALARM permission (which users can revoke in settings) or USE_EXACT_ALARM, which the store only allows for real alarm-clock and calendar apps. Alarms are lost when the device reboots, so apps listen for BOOT_COMPLETED and set them again. An alarm should usually only start a short job or post a notification, not do long work.
  • WorkManager is the default for work that must eventually run, with constraints and retries.
  • Doze and App Standby: when the device is idle, the system defers jobs, alarms and network access to maintenance windows, and puts rarely used apps in "buckets" that limit how often they can run. Foreground services and user-visible work are exempt, ordinary background tasks are not.

The practical rule: do the least work in the background, as late as possible, and let the system choose the moment. If you need something to happen immediately and invisibly, redesign it.

Push notifications: FCM, OneSignal and channels

Everything so far assumed that your own code decides when to notify. A push notification is different: a server sends a message over the internet, and the phone shows it even when your app is not running. On Android this travels through Firebase Cloud Messaging (FCM), Google's delivery service. Google Play services keeps one connection open for all apps, so your app does not need its own.

flowchart LR
    S["Your server"] -->|"send to a token"| F["FCM"]
    F -->|"one shared connection"| P["Google Play services<br/>on the phone"]
    P -->|"notification message,<br/>app in background"| T["System tray shows it"]
    P -->|"data message or<br/>app in foreground"| M["FirebaseMessagingService"]

The server never talks to the phone directly. FCM routes each message by a registration token.

Tokens

Each app installation gets a registration token, a long string that identifies it to FCM. Your server needs it to address that device. Tokens change: after a reinstall, a data restore, or when the user clears app data, and FCM can rotate them at any time. So you do two things: fetch the current token when the app starts and send it to your server, and override onNewToken to send each new one. Delete tokens that FCM reports as dead (the send call answers UNREGISTERED).

Notification messages and data messages

FCM has two message types, and they behave differently.

Notification message Data message
Payload Predefined fields: title, body, image Your own key-value pairs
App in background The system shows the notification; your code does not run Delivered to onMessageReceived
App in foreground Delivered to onMessageReceived Delivered to onMessageReceived
Control Little: easy to send, hard to customize Full: you build the notification yourself

A message can carry both. Then the background behavior follows the notification part, and the data arrives as extras in the intent of the tapped notification. Choose a notification message for simple announcements, and a data message when you need to decide what to show, update local data first, or pick a channel at run time. Data messages are also the right tool for "something changed, please sync". Mark time-critical messages with high priority, because normal-priority messages can be delayed while the device is in Doze.

Kotlin
// read-only example: receiving messages and tokens
class AppMessagingService : FirebaseMessagingService() {

    override fun onNewToken(token: String) {
        // Send it to your backend, but do not block here
        TokenUploadWorker.enqueue(applicationContext, token)
    }

    override fun onMessageReceived(message: RemoteMessage) {
        // Runs for data messages, and for notification messages while the app is open.
        // You only get a short window (about 20 seconds), so hand longer work to WorkManager.
        val title = message.data["title"] ?: message.notification?.title ?: return
        val body = message.data["body"] ?: message.notification?.body.orEmpty()
        showNotification(title, body, channelId = message.data["channel"] ?: "messages")
    }
}
XML
<!-- read-only example: AndroidManifest.xml -->
<service
    android:name=".AppMessagingService"
    android:exported="false">
    <intent-filter>
        <action android:name="com.google.firebase.MESSAGING_EVENT" />
    </intent-filter>
</service>

A high-priority message is one of the documented exceptions to the background-start rules above: FCM may start your messaging service for it. You still must not do long work there. Fetch or process in a CoroutineWorker through WorkManager.

Channels and permission still apply

A push is just another way to trigger a notification, so every rule from earlier in this lesson applies:

  • On Android 13+, you need POST_NOTIFICATIONS granted. Without it, a notification message is not shown, and a notification you post from onMessageReceived is dropped.
  • A notification message that the system shows uses the channel named by the message's android_channel_id field, or by com.google.firebase.messaging.default_notification_channel_id in the manifest. If neither names a channel that exists, FCM falls back to a default channel it creates itself ("Miscellaneous"), whose name and behavior you do not control. Create your channels at startup and declare one as the default.
  • The user's channel settings win, as before.

Third-party services

Many teams do not call FCM directly. Services like OneSignal, Braze, Airship or Customer.io wrap it: you add their SDK, it registers the token for you, and a dashboard lets non-developers send campaigns, segment users and schedule messages. Delivery to the phone is still FCM underneath on devices with Google Play services, so the same limits apply. The trade-offs are the usual ones: faster setup and a marketing interface against another SDK in your app, another processor of your users' data (check your privacy obligations) and a dependency on the vendor. If you only need messages that your own backend sends to known users, plain FCM through the Firebase Admin SDK is free and enough. For the full Firebase setup (project, google-services.json, BoM), see Firebase on Android.

A stand-in for the delivery rules

The stand-in below models what happens when a message arrives: whether the system or your service handles it, and the permission and channel checks before anything is shown.

Kotlin FCM message routing (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Cases 1 and 5 are the two silent failures developers usually meet first: a missing permission, and a channel ID that the server and the app disagree on.

Common mistakes

  • Doing work directly in onStartCommand. A service runs on the main thread, so a slow call freezes the app.
  • Forgetting stopSelf(). The service keeps the process alive and the notification stays.
  • Calling startForeground too late or without a type. On modern Android this crashes the app.
  • Never creating the channel, or misspelling its ID. The notification is dropped without an error on screen.
  • Asking for POST_NOTIFICATIONS at app launch. Ask in context; most users deny a request with no reason.
  • Designing channels after release. Importance cannot be raised later, so you cannot fix a channel that was created too quiet.
  • Using a foreground service because "it keeps working". If the user would not miss it, use WorkManager instead.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A service is both started and bound. A client unbinds, but nobody called stopSelf(). What happens?

    A service runs while it is started or has bound clients. Unbinding removes only one of the two reasons.
  2. 2. On which thread does a Service run its callbacks by default?

    Services have no thread of their own. Slow work must be moved to a coroutine or to WorkManager.
  3. 3. Why can a notification posted on Android 13 or later silently never appear?

    All three conditions drop or block the notification. They are the first things to check when a notification does not show.
  4. 4. Your app created the channel "sync" with IMPORTANCE_LOW and later ships an update that creates it again with IMPORTANCE_HIGH. What do existing users get?

    The system keeps the existing channel's behavior. If you want a louder channel, you need a new channel ID.
  5. 5. Which tool fits "upload the log file when the device is charging and on Wi-Fi"?

    That is deferrable work with conditions, the exact job WorkManager was designed for.

Summary

  • A service is a component without UI that runs while it is started or bound; it runs on the main thread inside your process.
  • Foreground services show an ongoing notification, declare a type in the manifest and cannot generally start from the background on Android 12 and later.
  • Notifications belong to channels the user controls; importance sets sound, pop-up and icon, and cannot be raised by the app after creation.
  • Android 13 and later need the runtime permission POST_NOTIFICATIONS; ask in context.
  • Use a foreground service for visible ongoing work, an exact alarm for exact times (with the special permission) and WorkManager for deferrable work.
  • Doze, App Standby and background limits mean you should do as little as possible in the background.
  • The Android code is read-only; the TryIts model service lifecycles, foreground rules and channel importance.

Next: Room Database Basics