skip to content

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%

answer

  1. body tap versus button tap
  2. activity for tap, receiver for work
  3. back stack for a regular screen
  4. up to three buttons, no duplicate
  5. distinct request codes per machine

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.

solid answer

~40 s

The body tap is `setContentIntent()`: a `PendingIntent` to the screen the notification is about, built with `TaskStackBuilder.addNextIntentWithParentStack()` so Back leads through the app's normal hierarchy, plus `setAutoCancel(true)` so the tap clears it. A button is `addAction()` with an icon, a label and its own `PendingIntent`; for 'Restart cycle' that is `PendingIntent.getBroadcast()` to a `BroadcastReceiver` that sends the restart and then cancels or updates the notification by ID. A notification takes up to three buttons, and a button must not repeat what the tap does. Each machine gets its own request code so two machines never share one `PendingIntent`, and from API 31 `setAuthenticationRequired(true)` makes a locked phone unlock before the restart runs.

code

kotlin · 21 lines
kotlin
fun restartAction(context: Context, machineId: Int): NotificationCompat.Action {
    val restart = Intent(context, MachineActionReceiver::class.java)
        .setAction(ACTION_RESTART_CYCLE)
        .putExtra(EXTRA_MACHINE_ID, machineId)
    val pending = PendingIntent.getBroadcast(
        context, machineId, restart, PendingIntent.FLAG_IMMUTABLE
    )
    return NotificationCompat.Action.Builder(R.drawable.ic_restart, "Restart cycle", pending)
        .setShowsUserInterface(false)
        .setAuthenticationRequired(true)
        .build()
}

fun openMachine(context: Context, machineId: Int): PendingIntent? =
    TaskStackBuilder.create(context)
        .addNextIntentWithParentStack(
            Intent(context, MachineActivity::class.java).putExtra(EXTRA_MACHINE_ID, machineId)
        )
        .getPendingIntent(
            machineId, PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
        )

go deeper

for a junior

Recall that setContentIntent handles the body tap and addAction adds a button with its own PendingIntent, and that setAutoCancel clears the notification on tap.

for a middle

Explain the regular versus special activity patterns for the tap, why a background action goes to a BroadcastReceiver, and the three-button limit.

for a senior

Show you catch shared request codes, clear or update the notification after an action, and require unlock for actions that change something real.

for a principal

Set a team rule for notification actions: each must be safe to run without opening the app, idempotent if fired twice, and reviewed for what a locked phone may trigger.

## Two entry points with different jobs A notification has one **content intent**, fired when the user taps the notification body, and up to **three action buttons**, each with its own intent. They answer different questions: | | Tap on the body | Action button | |---|---|---| | Builder call | `setContentIntent(pendingIntent)` | `addAction(icon, title, pendingIntent)` or `addAction(NotificationCompat.Action)` | | Usual target | An `Activity` showing what the notification is about | A `BroadcastReceiver` (or an activity when the action needs UI) | | Removal | `setAutoCancel(true)` cancels the notification on tap | Your handler cancels or updates it by ID | | Rule | Every notification must respond to a tap | Must not duplicate the tap; at most three | Both take a `PendingIntent`: a token that lets the system UI start your component later with your app's identity. How a `PendingIntent` works, and when it must be mutable, is covered with Android intents; here it is enough that these intents can be immutable, so `FLAG_IMMUTABLE` is the right flag. ## Wiring the tap so Back works The navigation guide splits tap targets into two kinds: 1. **A regular activity**, part of the app's normal flow, such as the machine detail screen. Declare `android:parentActivityName` on it in the manifest, then build the intent with `TaskStackBuilder.create(context).addNextIntentWithParentStack(intent).getPendingIntent(requestCode, flags)`. The resulting task holds the whole parent stack, so Back goes to the visit list and then home instead of straight out of the app. 2. **A special activity** that exists only to extend the notification. Start it in a fresh task with `FLAG_ACTIVITY_NEW_TASK or FLAG_ACTIVITY_CLEAR_TASK` and give it `android:taskAffinity=""` and `android:excludeFromRecents="true"` in the manifest, so it does not join the app's main task or linger in Recents. `setAutoCancel(true)` makes the system remove the notification when the user taps it in the panel. ## Wiring an action that works without opening the app For 'Restart cycle' the user wants the machine restarted, not a screen: - Build an explicit `Intent` to your receiver with an action string and the machine ID as an extra, and wrap it with `PendingIntent.getBroadcast()`. - Use `NotificationCompat.Action.Builder(icon, title, pendingIntent)` to set extras on the button: `setShowsUserInterface(false)` declares that it opens no UI, and `setAuthenticationRequired(true)` (honoured from API 31) makes the system ask a locked device to unlock before it sends the intent, sensible for a button that controls a machine. - In the receiver, keep `onReceive()` short: hand the network call to background work, then call `NotificationManagerCompat.cancel(id)` or post an updated notification ("Restarting washer 4...") with the same ID. Do not rely on `setAutoCancel()` for this; it is documented for a tap on the notification. - A receiver used only by your own notifications does not need to be exported; receiver declaration is covered with Android broadcasts. ## Picking the component behind each button | Button | Component | Why | |---|---|---| | Restart cycle | `BroadcastReceiver` via `getBroadcast()` | Does work in the background without interrupting what is on screen | | Choose another program | `Activity` via `getActivity()` | Needs a screen, so leave `setShowsUserInterface()` at its default `true` | | Dismissed by the user | `setDeleteIntent()` | Fires when the user clears the notification explicitly, useful for analytics or stopping reminders | ## Request codes: one machine, one PendingIntent The system treats two `PendingIntent`s as the same when their intents match on action, data, type, class and categories; **extras are ignored**. If washer 3 and washer 4 both use request code 0 and the same action, the second notification can end up firing washer 3's intent, or with `FLAG_UPDATE_CURRENT` silently rewrite it. Give each machine (or notification ID) its own request code, or put the machine in the intent's data URI. ## System-generated actions From **Android 10 (API 29)** the platform may add suggested replies and contextual actions to notifications that do not provide their own. For an alert whose buttons are deliberate, `setAllowSystemGeneratedContextualActions(false)` on the builder opts out of the contextual ones. ## Review checklist - The tap opens the screen for *this* machine, with a back stack that makes sense. - No button repeats the tap action, and there are at most three. - Every button's `PendingIntent` is unique per machine. - The handler clears or updates the notification once the action is done.

  • Tapping the notification opens the machine screen, but Back exits the app instead of returning to the visit list; what is missing?
    The tap intent was built with a plain `PendingIntent.getActivity()` for a regular screen. Declare `android:parentActivityName` on the machine activity and build the intent with `TaskStackBuilder.addNextIntentWithParentStack()` and `getPendingIntent()`, which creates the parent stack in the new task so Back walks up through the app.
  • Two machines' 'Restart cycle' buttons both restart washer 3; why?
    Both `PendingIntent`s were created with the same request code and an intent that differs only in extras, and extras are ignored when the system matches pending intents. The second one reused, or with `FLAG_UPDATE_CURRENT` overwrote, the first. Use the machine ID as the request code or encode it in the intent's data URI.

  • An action button should open the same screen as the tap
  • setAutoCancel also removes the notification when an action button is pressed
  • Extras make two PendingIntents with the same request code distinct
  • A notification can carry as many action buttons as you add
  • A plain getActivity intent gives a regular screen its back stack

Assumes API 37 and androidx.core 1.19.1; every PendingIntent must declare its mutability from Android 12 (API 31), and setAuthenticationRequired takes effect from API 31.