skip to content

Notifications & Channels

Posting Android notifications with NotificationCompat: channels whose importance is fixed once created, the Android 13 POST_NOTIFICATIONS permission, tap and action intents, and direct reply.

on this pageshow

explore

questions

6

With NotificationCompat, how do you build and post a 'your washer is done' notification on Android 8.0 and later, channel included?

level: juniorimportance: must knowfreq 80%

answer

  1. three pieces: channel, builder, manager
  2. channel registered once, at startup
  3. the one required visible field
  4. notify takes an int ID
  5. API 26 channels, API 33 permission

basics

~10 s

Register a NotificationChannel with an importance once at startup, build the notification with NotificationCompat.Builder(context, channelId) and at least a small icon, title, text and tap intent, then post it with NotificationManagerCompat.notify(id, notification).

solid answer

~30 s

Since Android 8.0 (API 26) every notification belongs to a channel, so at app start I register one, for example `machine_done`, through `NotificationManagerCompat.createNotificationChannel()` with `NotificationChannelCompat.Builder(id, IMPORTANCE_DEFAULT)`; re-registering it with the same values changes nothing, and the compat call does nothing below API 26. Then I build with `NotificationCompat.Builder(context, "machine_done")`: `setSmallIcon()` is the one required field, plus `setContentTitle()`, `setContentText()`, `setPriority()` for Android 7.1 and lower, `setContentIntent()` with a `PendingIntent` to the visit screen and `setAutoCancel(true)`. Finally `NotificationManagerCompat.from(context).notify(id, builder.build())`, after checking `POST_NOTIFICATIONS` on Android 13+. I keep the ID: the same ID updates or cancels that notification later.

code

kotlin · 32 lines
kotlin
const val CHANNEL_MACHINE_DONE = "machine_done"

fun createChannels(context: Context) {
    val channel = NotificationChannelCompat.Builder(
        CHANNEL_MACHINE_DONE, NotificationManagerCompat.IMPORTANCE_DEFAULT
    )
        .setName(context.getString(R.string.channel_machine_done))
        .setDescription(context.getString(R.string.channel_machine_done_desc))
        .build()
    NotificationManagerCompat.from(context).createNotificationChannel(channel)
}

fun postMachineDone(context: Context, machine: String, notificationId: Int) {
    val openVisit = PendingIntent.getActivity(
        context, notificationId,
        Intent(context, VisitActivity::class.java),
        PendingIntent.FLAG_IMMUTABLE
    )
    val notification = NotificationCompat.Builder(context, CHANNEL_MACHINE_DONE)
        .setSmallIcon(R.drawable.ic_washer)
        .setContentTitle("Washer $machine is done")
        .setContentText("Your laundry is ready to collect")
        .setPriority(NotificationCompat.PRIORITY_DEFAULT)
        .setContentIntent(openVisit)
        .setAutoCancel(true)
        .build()
    if (ContextCompat.checkSelfPermission(context, Manifest.permission.POST_NOTIFICATIONS)
        == PackageManager.PERMISSION_GRANTED
    ) {
        NotificationManagerCompat.from(context).notify(notificationId, notification)
    }
}

go deeper

for a junior

Recall the order: register a channel at startup, build with NotificationCompat.Builder(context, channelId) including a small icon, then post with NotificationManagerCompat.notify and a stable ID.

for a middle

Explain why priority only matters on 7.1 and lower, why registering an existing channel is harmless, and how the same ID updates or cancels a notification later.

for a senior

Show you design channel IDs as a long-lived contract, guard posting with the Android 13 permission check, and keep one builder path for both local events and push data.

for a principal

Treat the channel list as user-facing settings the team owns for years: few, clearly named kinds of alert, reviewed before release because behaviour cannot be changed afterwards.

## Three pieces, three owners Posting an Android notification always involves the same three objects, and most bugs come from mixing up which one decides what: - **`NotificationChannel`** (or its wrapper `NotificationChannelCompat`) decides *how* notifications behave: importance, sound, vibration, lights, badge. It is registered with the system once and from then on belongs to the user. - **`NotificationCompat.Builder`** decides *what* a single notification shows: icon, title, text, style, tap intent, actions. - **`NotificationManagerCompat`** posts, updates and cancels notifications by an integer ID (and optional tag). ## Step 1: register the channel at startup Starting in **Android 8.0 (API level 26)**, every notification must be assigned to a channel. If an app targeting API 26 or higher posts to a channel ID that was never created, the notification does not appear and the system logs an error; the developer option **Show notification channel warnings** turns that into an on-screen toast on a test device. Only apps targeting API 25 or lower fall back to the reserved `NotificationChannel.DEFAULT_CHANNEL_ID` (`"miscellaneous"`). 1. Pick a stable channel ID per kind of notification (`machine_done`, `attendant_messages`), a user-visible name and an importance. 2. Register it with `createNotificationChannel()` in `Application.onCreate()` or before the first post. 3. Call it on every start without worry: creating a channel that already exists with its original values does nothing. The platform `NotificationChannel` class exists only from API 26, so code that uses it directly needs an `SDK_INT` guard. `NotificationManagerCompat.createNotificationChannel()` does nothing on older releases, which lets `NotificationChannelCompat.Builder(id, importance)` code skip the guard. ## Step 2: build the notification `NotificationCompat.Builder(context, channelId)` takes the channel ID in its constructor; the single-argument `Builder(context)` is deprecated because every posted notification must name a channel. Releases before 8.0 simply ignore the ID. | Builder call | Why it is there | |---|---| | `setSmallIcon()` | The only required visible content; without a valid small icon `notify()` throws `IllegalArgumentException` ("Invalid notification (no valid small icon)") | | `setContentTitle()` / `setContentText()` | The collapsed title and one line of text | | `setStyle(NotificationCompat.BigTextStyle().bigText(...))` | Lets longer text expand instead of being cut to one line | | `setPriority()` | Used on Android 7.1 and lower; ignored from 8.0 in favour of the channel's importance | | `setContentIntent()` + `setAutoCancel(true)` | Opens the visit screen on tap and removes the notification when tapped | ## Step 3: post it `NotificationManagerCompat.from(context).notify(id, notification)` shows it. The method is annotated `@RequiresPermission(POST_NOTIFICATIONS)`: on **Android 13 (API 33)** and later the user must have granted that runtime permission, or nothing appears. `ContextCompat.checkSelfPermission(context, Manifest.permission.POST_NOTIFICATIONS)` is the check, and below API 33 it falls back to `areNotificationsEnabled()`. The same builder code runs when the alert comes from a push: a data message handed to the app's messaging service is turned into a notification here, while receiving that message is the Firebase Cloud Messaging lesson. ## Lock screen and the expanded form Two more builder calls decide what the notification reveals and how much room it gets: - `setVisibility()` controls the **lock screen**: `VISIBILITY_PUBLIC` shows everything, `VISIBILITY_PRIVATE` shows only basic information such as the icon and title, and `VISIBILITY_SECRET` shows nothing. With `VISIBILITY_PRIVATE` you can attach a redacted copy through `setPublicVersion()`, for example "A machine has finished" without the customer's locker number. The user can still override this per channel. - A **style** such as `BigTextStyle`, `InboxStyle` or `MessagingStyle` replaces the one-line collapsed text with an expanded layout when the user opens the notification; the collapsed form still uses the title and content text. ## Updating, removing and limits - Calling `notify()` again with the **same ID** replaces the notification; if the user already dismissed it, a new one is posted. - `setOnlyAlertOnce(true)` keeps updates from making a sound or vibrating again. - Since **Android 8.1 (API 27)** an app's notifications make a sound at most once per second, and very frequent updates to one notification may be dropped. - `cancel(id)` removes one notification, `cancelAll()` removes all of the app's notifications, and `setTimeoutAfter()` removes it after a duration. ## Common mistakes - Raising `setPriority()` to make an alert pop up on Android 8.0 and later: the channel's importance decides that. - Creating the channel with different settings on each launch and expecting the new sound or importance to apply: the user owns an existing channel's behaviour. - Generating a fresh random ID for each update, which stacks duplicates instead of replacing one notification.

  • What happens when you call NotificationManagerCompat.notify again with the same ID?
    The existing notification is replaced in place; if the user already dismissed it, a new one is posted. Add `setOnlyAlertOnce(true)` so the update does not sound or vibrate again, and avoid updating many times a second, because the system may drop updates. Keep the ID somewhere you can reach later, since `cancel(id)` needs it too.
  • A customer runs three machines in one visit; how do you keep their alerts together in the shade?
    Give every alert of that visit the same `setGroup(visitKey)` and post one extra summary notification with `setGroup(visitKey)` and `setGroupSummary(true)`, often an `InboxStyle` listing each machine, under a constant ID you update as alerts arrive. Notification groups are unrelated to `NotificationChannelGroup`, which only organises channels in settings. Without a group key, the system may still bundle four or more alerts on its own.
  • Why reach for NotificationChannelCompat instead of the platform NotificationChannel?
    The platform class exists only from API 26, so every use needs an `SDK_INT` check when minSdk is 24 or 25. `NotificationChannelCompat.Builder` plus `NotificationManagerCompat.createNotificationChannel()` do nothing on older releases, so the same startup code runs everywhere without a guard.

A channel is the mail slot type a resident has agreed to (letters, parcels, urgent), and the builder is the envelope: you can write anything on the envelope, but you cannot turn a letter slot into a doorbell after the resident set it up.

  • setPriority(PRIORITY_HIGH) makes the alert pop up on Android 8 and later
  • The channel ID in the builder is only a label the system ignores
  • Posting to a channel that was never created throws an exception
  • Title and text are enough; the small icon is optional
  • Re-creating a channel at launch with a new sound updates it for everyone

Assumes API 37 and androidx.core 1.19.1; channels are required from Android 8.0 (API 26) and posting needs POST_NOTIFICATIONS from Android 13 (API 33).

open as a page

On Android 13 and later, how does an app get the POST_NOTIFICATIONS permission, and how does its target SDK change when the dialog appears?

level: middleimportance: must knowfreq 70%

basics

~20 s

POST_NOTIFICATIONS is a runtime permission from Android 13 (API 33): declare it, then request it. Apps targeting 33+ choose when the dialog appears; for targets of 32 or lower the system shows it once a channel exists and an activity starts.

open as a page

With NotificationCompat, how do you build and keep updating the ongoing notification a foreground service shows while a wash cycle runs?

level: middleimportance: should knowfreq 40%

basics

~20 s

Post 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.

open as a page

With NotificationCompat, how do a notification's tap intent and a 'Restart cycle' action button differ, and how do you wire each one?

level: middleimportance: should knowfreq 55%

basics

~20 s

The tap intent, set with setContentIntent, opens the matching screen with a proper back stack; an action button, added with addAction, fires its own PendingIntent, often a broadcast that restarts the cycle without opening the app.

open as a page

After release, an Android app raises its 'machine_done' NotificationChannel from IMPORTANCE_DEFAULT to IMPORTANCE_HIGH in code, yet existing users get no heads-up alerts; why, and what do you do?

level: seniorimportance: should knowfreq 50%

basics

~20 s

Once a channel exists the user owns its behaviour: re-registering it can only lower its importance, never raise it. For heads-up alerts, create a new channel ID at IMPORTANCE_HIGH and delete the old one, or link users to its settings.

open as a page

In an Android app, a NotificationCompat direct-reply action shows its text field, but RemoteInput.getResultsFromIntent returns null in the receiver; why, and how do you fix it?

level: seniorimportance: should knowfreq 35%

basics

~20 s

The reply action's PendingIntent was created with FLAG_IMMUTABLE, so the system cannot add the typed text to the intent it sends. Create that one PendingIntent with FLAG_MUTABLE on an explicit intent, and re-post the notification after handling the reply.

open as a page