With NotificationCompat, how do you build and keep updating the ongoing notification a foreground service shows while a wash cycle runs?
answer
- a quiet channel of its own
- ongoing, alert once, same ID
- a countdown the system ticks
- shown at once from Android 12
- the finish alert needs another channel
basics
~20 sPost it on its own low-importance channel, mark it setOngoing(true) and setOnlyAlertOnce(true), pass it to startForeground under a non-zero ID, and update it by calling notify with that same ID; the 'done' alert goes on a separate, louder channel.
solid answer
~40 sI give the status notification its own channel at `IMPORTANCE_LOW`, so it shows without sound, and build it with `setOngoing(true)`, `setOnlyAlertOnce(true)`, `setCategory(CATEGORY_SERVICE)` and a tap intent to the visit. For the time left I prefer `setWhen(endTime)` with `setUsesChronometer(true)` and `setChronometerCountDown(true)`, which the system ticks itself, over reposting every minute; `setProgress()` suits a percentage. The service passes it to `startForeground()` with a non-zero ID, and later changes go through `NotificationManagerCompat.notify()` with that same ID. On Android 12+ `setForegroundServiceBehavior(FOREGROUND_SERVICE_IMMEDIATE)` stops the system delaying it. When the cycle ends I post the 'done' alert with a different ID on the default-importance channel, because the low channel makes no sound unless the user raises it.
code
kotlin · 17 linesfun cycleNotification(context: Context, machine: String, endsAt: Long): Notification =
NotificationCompat.Builder(context, CHANNEL_CYCLE_STATUS) // IMPORTANCE_LOW channel
.setSmallIcon(R.drawable.ic_washer)
.setContentTitle("Washer $machine running")
.setContentText("Time left until your cycle ends")
.setWhen(endsAt)
.setUsesChronometer(true)
.setChronometerCountDown(true)
.setOngoing(true)
.setOnlyAlertOnce(true)
.setCategory(NotificationCompat.CATEGORY_SERVICE)
.setForegroundServiceBehavior(NotificationCompat.FOREGROUND_SERVICE_IMMEDIATE)
.setContentIntent(openVisit(context))
.build()
// In the service: ServiceCompat.startForeground(this, CYCLE_NOTIFICATION_ID, notification, type)
// If the end time changes: notify(CYCLE_NOTIFICATION_ID, cycleNotification(...)) with the same IDgo deeper
Recall that a foreground service must show a notification, built with NotificationCompat like any other, and that you update it by posting again with the same ID.
Explain why the status and the finish alert need separate channels, what setOnlyAlertOnce and the chronometer calls do, and what FOREGROUND_SERVICE_IMMEDIATE changes on Android 12.
Show you anticipate a user who denied POST_NOTIFICATIONS, update rate limits, and a finish alert that silently inherits a quiet channel.
Keep one shared builder for every long-running notification, foreground services and WorkManager alike, so channels, categories and update rules stay consistent across features.
## What this notification is for A **foreground service** has to show a notification for as long as it runs; that is how the user knows the app is doing work. Choosing the service, its type and when it may start is the subject of the services lesson. This one is about the notification itself: which channel it uses, how it is built and how it is kept current. The same object is what a WorkManager `ForegroundInfo` carries, so the advice applies there too. Take a laundromat app whose service keeps a connection to the machine while the cycle runs and shows "Washer 4 - 23 min left". ## A channel of its own The status line and the "your washer is done" alert need different behaviour, and behaviour lives on the **channel**: | Channel | Importance | Why | |---|---|---| | `cycle_status` | `IMPORTANCE_LOW` | Visible in the shade, makes no sound; right for something on screen for 45 minutes | | `machine_done` | `IMPORTANCE_DEFAULT` or higher | Makes a sound; this is the alert the user actually wants | `IMPORTANCE_MIN` is documented as the wrong choice for a notification passed to `startForeground()`: from Android 8.0 the system then shows its own, higher-priority notification about the app running in the background (on 7.1 and lower the guide asks for at least `PRIORITY_LOW`). A low-importance channel is the usual home for it. ## Building it - `setOngoing(true)` marks it as ongoing. The platform documentation says ongoing notifications cannot be dismissed by the user on a locked device or by notification listeners, and only some kinds (call, device management, media) are non-dismissible on an unlocked one, so do not assume it can never be swiped away. - `setOnlyAlertOnce(true)` keeps each update from alerting again if the user raises the channel's importance. - `setCategory(NotificationCompat.CATEGORY_SERVICE)` labels it as a running background service. - A **countdown** with `setWhen(endTimeMillis)`, `setUsesChronometer(true)` and `setChronometerCountDown(true)` (API 24+) is drawn and ticked by the system, so the app does not repost every minute; `setProgress(max, progress, false)` fits a percentage instead. - `setContentIntent()` opens the visit screen, and a 'Stop' action can be added like any other action button. - `setForegroundServiceBehavior(FOREGROUND_SERVICE_IMMEDIATE)` matters from **Android 12 (API 31)**: by default the system may defer showing a foreground service's notification for a short time, and this constant asks for it at once. It has no effect on earlier releases. ## Countdown or progress bar | Need | Builder calls | Repost needed? | |---|---|---| | Time left until a known end | `setWhen(end)`, `setUsesChronometer(true)`, `setChronometerCountDown(true)` | Only when the end time changes | | Elapsed time since a start | `setWhen(start)`, `setUsesChronometer(true)` | No | | Percentage of a measurable job | `setProgress(max, current, false)` | Yes, at each step worth showing | | Unknown duration | `setProgress(0, 0, true)` | No, until it finishes | ## Posting and updating 1. The service passes the built notification to `ServiceCompat.startForeground()` with a **positive, non-zero ID**. 2. Each later change rebuilds it and calls `NotificationManagerCompat.from(context).notify(sameId, notification)`. A different ID would add a second notification instead of updating the first. 3. Keep updates infrequent: the system may drop updates to one notification posted many times a second. ## When the user denied POST_NOTIFICATIONS On **Android 13 (API 33)** and later the app does not need `POST_NOTIFICATIONS` to start a foreground service, and it must still provide the notification. If the user denied the permission, the service's notice appears in the Task Manager but not in the notification drawer. The 'done' alert is an ordinary notification, so it is not shown at all without the grant. ## When the cycle ends - Post the finish alert on `machine_done` with its **own ID**. Updating the status notification to say "Done" leaves it on the low channel, where it makes no sound. - Then stop the service and remove the status notification; how the service leaves the foreground is covered with services. ## Mistakes worth catching in review - Using one channel for status and alerts, then raising its importance so the alert sounds, which makes every status update loud too. - Reposting every second to animate a timer the chronometer could draw. - Building the notification with `Builder(context)` and no channel, or with ID 0 for the service.
- The cycle's 'done' alert never makes a sound; the code calls notify with the status notification's ID and new text. Why?Updating that ID keeps the notification on the low-importance status channel, which makes no sound, and `setOnlyAlertOnce(true)` suppresses alerts on updates anyway. Post the finish alert as a separate notification with its own ID on a channel whose importance makes a sound, then remove the status one when the service stops.
- Why not update the notification every second to show a ticking timer?Each update is a full repost the system must render, and it may drop updates to one notification posted many times a second. `setWhen()` with `setUsesChronometer(true)` and `setChronometerCountDown(true)` lets the system tick the countdown itself, so the app reposts only when the end time actually changes.
- Without POST_NOTIFICATIONS the service notice still shows in the drawer
- Updating the status notification to 'Done' will make it sound
- setOngoing(true) means the user can never swipe it away anywhere
- IMPORTANCE_MIN is the right channel for a foreground service notice
- Each progress update should be posted under a new notification ID
Assumes API 37 and androidx.core 1.19.1; setForegroundServiceBehavior takes effect from Android 12 (API 31), and the POST_NOTIFICATIONS rules for foreground-service notices apply from Android 13 (API 33).