Notifications and channels
Why it matters
- On Android 8+ every notification must name a channel that exists. A notification posted to a missing channel is dropped with only a logcat warning, which is one of the most common notification bugs.
- Android 13 (API 33) made notifications a runtime permission. An app that never asks loses all its notifications, and
notify()does not throw. - After a channel is created the user owns its settings. Code that expects to change a channel's importance later does not work.
- Interviewers probe channels, importance,
POST_NOTIFICATIONSandPendingIntentmutability to check that you know the current rules rather than old snippets.
The simple explanation
- A notification channel is a labelled mailbox slot in an apartment building.
- You install the slot and pick its first settings: sound, vibration, how loud it is.
- After that the tenant (the user) controls the slot: they can mute it or turn it off, and you cannot turn it back up.
- In newer buildings (Android 13+) you also need the tenant's key (
POST_NOTIFICATIONS) before you can deliver anything.
A notification channel is a NotificationChannel you register with NotificationManager.createNotificationChannel() before posting. Channels are required from API 26 (Android 8.0). Every NotificationCompat.Builder(context, channelId) carries a channel id, and on API 26+ the channel's importance decides how the notification behaves; the builder's setPriority() is used only on Android 7.1 and lower.
| Importance | Sound | Status bar icon | Heads-up | Typical use |
|---|---|---|---|---|
IMPORTANCE_MIN | No | No | No | Background info, weather |
IMPORTANCE_LOW | No | Yes | No | Progress, non-urgent updates |
IMPORTANCE_DEFAULT | Yes | Yes | No | Most alerts |
IMPORTANCE_HIGH | Yes | Yes | Yes | Messages, urgent time-sensitive alerts |
Key rules by API level:
- API 26 (Android 8): the channel must exist before
notify(). Creating it is safe to repeat, so create channels at app start, for example inApplication.onCreate(). - After creation: calling
createNotificationChannel()again with the same id can update the name and description, and can lower the importance only if the user has not changed the channel. It cannot raise importance. To change behaviour, create a channel with a new id and delete the old one. - API 31 (target 31, Android 12): every
PendingIntentmust setFLAG_IMMUTABLEorFLAG_MUTABLE; otherwise creating it throwsIllegalArgumentException. - API 33 (target 33, Android 13):
POST_NOTIFICATIONSis a runtime permission. Without it,notify()posts nothing and throws nothing. - API 34 (Android 14): full-screen intents (
setFullScreenIntent) are allowed by default only for calling and alarm apps; other apps checkNotificationManager.canUseFullScreenIntent().
Use NotificationCompat.Builder and NotificationManagerCompat, which handle version differences for you. A small icon is required: posting without one throws IllegalArgumentException.
For grouped notifications, call setGroup(key) on each notification and post one extra notification with setGroup(key) and setGroupSummary(true). On Android 7+ the system shows the group as one expandable bundle.
Notes
- Create channels at app start (
Application.onCreate()or an initializer). Repeated calls with the same id do not reset the user's choices. - Channel ids are permanent keys for the user's settings. Keep them stable constants; renaming an id creates a new channel with default settings.
- Only the user can raise a channel's importance or turn sound back on. Code can lower importance (if the user has not touched the channel), delete the channel, or create a new one. Deleted channels are still shown in the app's settings as a count, so do not churn ids.
- On API 26+ the channel importance wins;
setPriority()matters only on Android 7.1 and lower. A heads-up notification needs anIMPORTANCE_HIGHchannel on 26+. POST_NOTIFICATIONS(Android 13) is requested withActivityResultContracts.RequestPermission(). New installs of apps targeting 33+ start with notifications off. For apps targeting 32 or lower, Android 13 shows the prompt itself when the app creates its first channel.- If the user denies the permission twice, the system stops showing the dialog. Check
shouldShowRequestPermissionRationale()and send the user toSettings.ACTION_APP_NOTIFICATION_SETTINGSwithSettings.EXTRA_APP_PACKAGE. - Check
NotificationManagerCompat.from(context).areNotificationsEnabled()before relying on a notification; it is false when the permission is denied or the user turned notifications off. FLAG_IMMUTABLEexists since API 23 andFLAG_MUTABLEsince API 31; neither is a default. UseFLAG_IMMUTABLEunless the system must fill in the intent, for example an inline reply withRemoteInputor a bubble. On target 34 a mutablePendingIntentmust wrap an explicit intent.- A missing small icon throws
IllegalArgumentExceptionwhen you post. On Android 5+ the small icon is drawn as a white silhouette, so use a single-colour drawable with transparency. - Full-screen intents on Android 14:
USE_FULL_SCREEN_INTENTis granted by default only to calling and alarm apps. CheckcanUseFullScreenIntent()and offerSettings.ACTION_MANAGE_APP_USE_FULL_SCREEN_INTENT, or fall back to a high-importance notification.
Code example
A notifier that creates a channel at app start, checks the Android 13 permission, and posts a notification that opens the app, plus the permission request in an activity. It assumes minSdk 26.
// OrderNotifier.kt
import android.Manifest
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Build
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
import androidx.core.content.ContextCompat
object OrderNotifier {
private const val CHANNEL_ID = "order_updates" // stable: the user's settings are keyed by it
// Call from Application.onCreate(); safe to repeat
fun createChannel(context: Context) {
val channel = NotificationChannel(
CHANNEL_ID,
"Order updates",
NotificationManager.IMPORTANCE_DEFAULT,
).apply { description = "Shipping and delivery status" }
context.getSystemService(NotificationManager::class.java).createNotificationChannel(channel)
}
fun post(context: Context, orderId: Long, title: String, body: String) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU &&
ContextCompat.checkSelfPermission(context, Manifest.permission.POST_NOTIFICATIONS)
!= PackageManager.PERMISSION_GRANTED
) {
return // notify() would post nothing; show the update in the app instead
}
val intent = Intent(context, MainActivity::class.java).apply {
flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
putExtra("orderId", orderId)
}
val contentIntent = PendingIntent.getActivity(
context,
orderId.toInt(), // different request codes keep one PendingIntent per order
intent,
PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT,
)
val notification = NotificationCompat.Builder(context, CHANNEL_ID)
.setSmallIcon(R.drawable.ic_order) // required: posting without it throws
.setContentTitle(title)
.setContentText(body)
.setPriority(NotificationCompat.PRIORITY_DEFAULT) // Android 7.1 and lower only
.setContentIntent(contentIntent)
.setAutoCancel(true)
.build()
NotificationManagerCompat.from(context).notify(orderId.toInt(), notification)
}
}
// MainActivity.kt (inside a ComponentActivity)
private val requestNotifications =
registerForActivityResult(ActivityResultContracts.RequestPermission()) { granted ->
if (!granted) showInAppBanner("Turn on notifications to hear when your order ships")
}
private fun askForNotificationsIfNeeded() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
requestNotifications.launch(Manifest.permission.POST_NOTIFICATIONS)
}
}<!-- AndroidManifest.xml -->
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />createChannelruns at every start; the system keeps the existing channel and the user's changes.- The permission check makes the denied case explicit. Without it the call is silently a no-op on Android 13+, and lint warns that
notify()needs the permission. FLAG_IMMUTABLEsatisfies the Android 12 rule;FLAG_UPDATE_CURRENTrefreshes the extras if aPendingIntentfor the same order already exists.- Ask for the permission in context, for example after the user places an order, rather than on the first screen.
Run the idea in plain Kotlin
A model of how the system treats channel updates and posts: raising importance in code is ignored, lowering works only until the user changes the channel, and posts without a channel or without the Android 13 permission are dropped without an exception.
enum class Importance { MIN, LOW, DEFAULT, HIGH }
class Channel(val id: String, var name: String, var importance: Importance) {
var userModified = false
}
class FakeNotificationManager(private val apiLevel: Int, var permissionGranted: Boolean) {
private val channels = mutableMapOf<String, Channel>()
fun createNotificationChannel(id: String, name: String, importance: Importance) {
val existing = channels[id]
if (existing == null) {
channels[id] = Channel(id, name, importance)
println("create " + id + ": new channel, " + importance)
return
}
existing.name = name
if (importance < existing.importance && !existing.userModified) {
existing.importance = importance
println("create " + id + ": importance lowered to " + importance)
} else {
println("create " + id + ": importance stays " + existing.importance)
}
}
fun userChanges(id: String, importance: Importance) {
val ch = channels.getValue(id)
ch.importance = importance
ch.userModified = true
println("user sets " + id + " to " + importance)
}
fun notify(notificationId: Int, channelId: String) {
if (apiLevel >= 33 && !permissionGranted) {
println("notify " + notificationId + ": dropped, POST_NOTIFICATIONS not granted")
return
}
val ch = channels[channelId]
if (ch == null) {
println("notify " + notificationId + ": dropped, no channel " + channelId)
return
}
val style = if (ch.importance == Importance.HIGH) "heads-up" else "in shade"
println("notify " + notificationId + ": shown " + style + " on " + channelId)
}
}
fun main() {
val nm = FakeNotificationManager(apiLevel = 34, permissionGranted = true)
nm.notify(1, "chat")
nm.createNotificationChannel("chat", "Chat", Importance.DEFAULT)
nm.createNotificationChannel("chat", "Chat", Importance.HIGH)
nm.createNotificationChannel("chat", "Chat", Importance.LOW)
nm.userChanges("chat", Importance.HIGH)
nm.createNotificationChannel("chat", "Chat", Importance.MIN)
nm.notify(2, "chat")
nm.permissionGranted = false
nm.notify(3, "chat")
}Expected output:
notify 1: dropped, no channel chat
create chat: new channel, DEFAULT
create chat: importance stays DEFAULT
create chat: importance lowered to LOW
user sets chat to HIGH
create chat: importance stays HIGH
notify 2: shown heads-up on chat
notify 3: dropped, POST_NOTIFICATIONS not granted
In production
- A delivery app raised
targetSdkto 33 and shipped. Over the next weeks, new users on Android 13+ said they never got "driver arriving" alerts. - There were no crashes:
notify()was called as before, but the app never requestedPOST_NOTIFICATIONS, so for new installs notifications were off. - Existing users kept working, because they already held the permission (pre-granted when their device upgraded to Android 13, or granted through the prompt the system showed the old build). Internal testers were all existing users, which hid the bug.
- They added a
RequestPermission()launcher shown right after the first order is placed, with a one-line reason, instead of on the first screen. - When
areNotificationsEnabled()is false, the order screen shows an in-app banner with a button that opensSettings.ACTION_APP_NOTIFICATION_SETTINGS. - They logged the permission state at app start to analytics and added a fresh-install test on an Android 13+ emulator to the release checklist.
- A chat app shipped its "Messages" channel with
IMPORTANCE_DEFAULT. Product later wanted heads-up banners, so a release changed the code toIMPORTANCE_HIGH. - Existing users saw no change. The second
createNotificationChannel()call kept the existing channel's importance, because code can never raise it. Only fresh installs got heads-up notifications. - QA tested on clean emulators, so the release looked correct.
- They created a new channel
messages_v2withIMPORTANCE_HIGH, posted to it from then on, and deleted the old channel withdeleteNotificationChannel("messages"). - Users who had muted the old channel were shown a one-time in-app explanation instead of being silently switched to a louder channel.
- They added an upgrade test that installs the previous build, creates the channel, then installs the new build and checks which channel is used.
Common mistakes
- Posting before creating the channel. On API 26+ the notification is dropped and only a logcat warning ("No Channel found") appears. Create channels at app start.
- Expecting code to change a channel later.
createNotificationChannel()with the same id cannot raise importance or turn sound back on. Create a new channel id when the behaviour must change. - Never requesting POST_NOTIFICATIONS on Android 13+.
notify()silently posts nothing. Request the permission at a meaningful moment and handle the denied state in the UI. - Omitting FLAG_IMMUTABLE or FLAG_MUTABLE. On target 31+ creating the
PendingIntentthrowsIllegalArgumentException. Default toFLAG_IMMUTABLE; useFLAG_MUTABLEonly for cases likeRemoteInputreplies. - Forgetting setSmallIcon(). Posting throws
IllegalArgumentException. Use a single-colour icon with transparency, since the system draws it as a silhouette. - Using setFullScreenIntent without checking. On Android 14 most apps no longer have full-screen intent access by default; check
canUseFullScreenIntent()and provide a fallback. - Reusing one request code for different PendingIntents. With the same intent and request code,
FLAG_UPDATE_CURRENToverwrites the extras, so every notification opens the last item. Use a distinct request code per item.
Interview questions
Answer out loud first. Then reveal the answer and compare it at each depth.
“What is a notification channel and who controls its settings?”
“How do you handle the POST_NOTIFICATIONS permission on Android 13?”
“What PendingIntent flags are required on Android 12 and why?”
“How do you group notifications, and what changed for full-screen intents in Android 14?”
Quiz
On Android 8.0+, your app calls notify() with a channel id that was never created. What happens?
What happens if you call NotificationManagerCompat.notify() on Android 13+ when POST_NOTIFICATIONS is not granted?
Your app created a channel with IMPORTANCE_LOW. A new release needs heads-up notifications for existing users. What works?
Which PendingIntent flag should be your default on Android 12+?
0 of 4 answered
Mini task
15-minute exercise: channel, permission and grouped notifications
-
Create a channel. In
Application.onCreate(), create aNotificationChannelwith id"chat_messages", name"Chat"andIMPORTANCE_HIGH. -
Request the permission. In your main activity, register
ActivityResultContracts.RequestPermission()and launch it forManifest.permission.POST_NOTIFICATIONSfrom a button, only whenBuild.VERSION.SDK_INT >= 33. Add the permission to the manifest. -
Post a group. Post two message notifications (ids 2001 and 2002) with
setGroup("chat_group"), then a summary (id 2000) with the same group,setGroupSummary(true),setStyle(NotificationCompat.InboxStyle())and the title"2 new messages". -
Add a tap action. Give each message a content intent built with
PendingIntent.getActivity(..., FLAG_IMMUTABLE or FLAG_UPDATE_CURRENT)and a different request code per message, so each opens its own conversation. -
Verify. Grant the permission and check the shade: one expandable group, heads-up for new messages, and each tap opens the right conversation.
-
Break it on purpose. Change the channel's importance in code to
IMPORTANCE_LOWand then back toIMPORTANCE_HIGHwithout reinstalling, and see that it stays low. Then deny the permission in Settings and confirm nothing is posted and nothing crashes.
Done when: the group shows correctly, each notification opens its own item, and you have seen that code cannot raise a channel's importance and that a denied permission silently blocks posts.