Skip to main content

Implementing Notifications

1. Creating Notification Channels

Property Description Values
id Unique identifier for the channel "channel_id"
name User-visible name of the channel "My Channel"
description Human-readable description of the channel "Channel for app notifications"
importance Importance level affecting how notifications are displayed IMPORTANCE_DEFAULT, IMPORTANCE_HIGH, IMPORTANCE_LOW, IMPORTANCE_MIN
enableLights Whether to light up the device LED for notifications true, false
lightColor Color of the LED light (if enabled) Color.BLUE, Color.RED
enableVibration Whether to vibrate the device on notification true, false
vibrationPattern Custom vibration pattern (optional) longArrayOf(1000, 500, 1000)

Example: Creating a Notification Channel

val channel = NotificationChannel(
    "channel_id",
    "My Channel",
    NotificationManager.IMPORTANCE_DEFAULT
).apply {
    description = "Channel for app notifications"
    enableLights = true
    lightColor = Color.BLUE
    enableVibration = true
    vibrationPattern = longArrayOf(1000, 500, 1000)
}

val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notificationManager.createNotificationChannel(channel)

2. Building Notifications

Example: Basic Notification

val notification = NotificationCompat.Builder(context, "channel_id")
    .setSmallIcon(R.drawable.ic_notification)
    .setContentTitle("New Message")
    .setContentText("You have a new message")
    .setPriority(NotificationCompat.PRIORITY_DEFAULT)
    .build()

NotificationManagerCompat.from(context).notify(1, notification)
Property Description Values
setSmallIcon Small icon shown in the notification R.drawable.icon_name
setContentTitle Title of the notification String
setContentText Main text content of the notification String
setPriority Priority level of the notification PRIORITY_MIN, PRIORITY_LOW, PRIORITY_DEFAULT, PRIORITY_HIGH, PRIORITY_MAX
setChannelId Channel ID for grouping related notifications String
Note: Notifications require a notification channel to be displayed on Android 8.0+ (API level 26).

Example: Notification with Action

val intent = Intent(context, MainActivity::class.java)
val pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT)

val notification = NotificationCompat.Builder(context, "channel_id")
    .setSmallIcon(R.drawable.ic_notification)
    .setContentTitle("New Message")
    .setContentText("You have a new message")
    .setContentIntent(pendingIntent)
    .addAction(R.drawable.ic_reply, "Reply", pendingIntent)
    .build()

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

3. Setting Notification Content

Property Description Values
setContentTitle Sets the title of the notification CharSequence
setContentText Sets the main text content of the notification CharSequence
setSubText Secondary text shown below the content text CharSequence
setBigText Expands the notification to show more content CharSequence
setSummaryText Summary text for grouped notifications CharSequence

Example: Basic Notification Content

val notification = NotificationCompat.Builder(context, CHANNEL_ID)
    .setContentTitle("New Message")
    .setContentText("You have a new message from John")
    .setSubText("John Doe")
    .build()

Example: Expanded Notification

val bigText = "This is a very long message that will be displayed in an expanded notification. " +
    "It can contain multiple lines of text to provide more details."

val notification = NotificationCompat.Builder(context, CHANNEL_ID)
    .setContentTitle("Long Message")
    .setContentText("Short preview")
    .setBigText(bigText)
    .build()

4. Displaying Notifications

Property Description Values
notificationId Unique identifier for the notification Int
channelId Channel ID to group related notifications String
title Notification title String
contentText Main content text of the notification String
icon Resource ID for notification icon Int
sound Sound to play when notification is shown Uri
vibrate Pattern to vibrate the device LongArray

Example: Basic Notification

val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
val channelId = "my_channel"
val channelName = "My Notifications"

val channel = NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_DEFAULT)
notificationManager.createNotificationChannel(channel)

val builder = NotificationCompat.Builder(this, channelId)
    .setSmallIcon(R.drawable.ic_notification)
    .setContentTitle("Hello")
    .setContentText("This is a notification")
    .setPriority(NotificationCompat.PRIORITY_DEFAULT)

notificationManager.notify(1, builder.build())

Example: Notification with Actions

val actionIntent = Intent(this, MyReceiver::class.java)
actionIntent.action = "ACTION_CLICKED"
val pendingIntent = PendingIntent.getBroadcast(this, 0, actionIntent, PendingIntent.FLAG_UPDATE_CURRENT)

val builder = NotificationCompat.Builder(this, channelId)
    .setSmallIcon(R.drawable.ic_notification)
    .setContentTitle("Actionable Notification")
    .setContentText("Tap to perform action")
    .addAction(R.drawable.ic_action, "Action", pendingIntent)

notificationManager.notify(2, builder.build())
Note: Ensure that notification channels are created before displaying notifications to avoid silent notifications on Android 8.0+.

5. Adding Actions to Notifications

Action Description Code Example
addAction() Adds an action to the notification
val action = NotificationCompat.Action.Builder(
    R.drawable.ic_action,
    "Action Text",
    pendingIntent
).build()

notificationBuilder.addAction(action)
Note: Actions are only supported on Android 4.1 (API level 16) and above.

6. Using Notification Styles

Style Description Code Example
BigTextStyle Displays a large text content in the notification.
val notification = NotificationCompat.Builder(context, CHANNEL_ID)
    .setContentTitle("Big Text Style")
    .setContentText("Short text")
    .setStyle(NotificationCompat.BigTextStyle()
        .bigText("This is a very long text that will be displayed in the notification using BigTextStyle."))
    .build()
BigPictureStyle Displays a large image in the notification.
val notification = NotificationCompat.Builder(context, CHANNEL_ID)
    .setContentTitle("Big Picture Style")
    .setContentText("Short text")
    .setStyle(NotificationCompat.BigPictureStyle()
        .bigPicture(BitmapFactory.decodeResource(context.resources, R.drawable.large_image)))
    .build()
InboxStyle Shows a list of items in the notification.
val notification = NotificationCompat.Builder(context, CHANNEL_ID)
    .setContentTitle("Inbox Style")
    .setContentText("Short text")
    .setStyle(NotificationCompat.InboxStyle()
        .addLine("Item 1")
        .addLine("Item 2")
        .addLine("Item 3"))
    .build()
MessagingStyle Used for chat-like notifications, showing messages from different participants.
val participant = NotificationCompat.MessagingStyle.Message(
    "Hello there!",
    System.currentTimeMillis(),
    "John Doe"
)
val notification = NotificationCompat.Builder(context, CHANNEL_ID)
    .setContentTitle("Messaging Style")
    .setStyle(NotificationCompat.MessagingStyle()
        .setConversationTitle("Group Chat")
        .addMessage(participant))
    .build()
Note: Notification styles require Android API level 24 or higher for full support.

7. Setting Notification Priority and Category

Property Values Description
priority NotificationCompat.PRIORITY_MIN
NotificationCompat.PRIORITY_LOW
NotificationCompat.PRIORITY_DEFAULT
NotificationCompat.PRIORITY_HIGH
NotificationCompat.PRIORITY_MAX
Determines how much the notification should intrude into the user's space. Higher priority notifications are more likely to be shown as heads-up.
category NotificationCompat.CATEGORY_CALL
NotificationCompat.CATEGORY_MESSAGE
NotificationCompat.CATEGORY_EMAIL
NotificationCompat.CATEGORY_EVENT
NotificationCompat.CATEGORY_PROMO
NotificationCompat.CATEGORY_REMINDER
NotificationCompat.CATEGORY_SERVICE
NotificationCompat.CATEGORY_SYSTEM
NotificationCompat.CATEGORY_TRANSPORT
Indicates the type of notification, which helps the system and user understand its context and behavior.

Example: Setting Priority and Category

val notification = NotificationCompat.Builder(context, CHANNEL_ID)
    .setContentTitle("New Message")
    .setContentText("You have a new message.")
    .setPriority(NotificationCompat.PRIORITY_HIGH)
    .setCategory(NotificationCompat.CATEGORY_MESSAGE)
    .build()

8. Handling Notification Taps

Property Description Example
PendingIntent Used to launch an activity or service when a notification is tapped PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT)
Intent Defines the action to perform when tapped (e.g., open a screen) Intent(context, MainActivity::class.java)

Example: Handling Tap with Activity Launch

val intent = Intent(context, MainActivity::class.java)
intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
val pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT)

val notification = NotificationCompat.Builder(context, CHANNEL_ID)
    .setContentTitle("New Message")
    .setContentText("You have a new message")
    .setSmallIcon(R.drawable.ic_notification)
    .setContentIntent(pendingIntent)
    .build()
Note: Ensure the Intent includes appropriate flags like FLAG_ACTIVITY_NEW_TASK to properly launch the activity.

9. Updating and Canceling Notifications

Method Description Notes
NotificationManagerCompat.notify() Updates a notification that is already shown Must use the same ID as the original notification
NotificationManagerCompat.cancel() Cancels a notification by ID Does not require the notification to be visible
NotificationManagerCompat.cancelAll() Cancels all notifications Clears all notifications from the app

Example: Updating a Notification

val notificationManager = NotificationManagerCompat.from(context)
val builder = NotificationCompat.Builder(context, CHANNEL_ID)
    .setContentTitle("Updated Title")
    .setContentText("New content text")
    .setSmallIcon(R.drawable.ic_notification)

notificationManager.notify(notificationId, builder.build())

Example: Canceling a Notification

val notificationManager = NotificationManagerCompat.from(context)
notificationManager.cancel(notificationId)

Example: Canceling All Notifications

val notificationManager = NotificationManagerCompat.from(context)
notificationManager.cancelAll()
Note: When updating a notification, the new notification must use the same notificationId as the original to replace it.

10. Creating Grouped Notifications

Grouped notifications allow you to combine multiple related notifications into a single summary notification, improving user experience by reducing clutter.

Property Description Value
group Identifier for the group to which this notification belongs "my_group"
groupSummary Set to true for the summary notification in a group false
sortKey Used to sort notifications within a group "001"

Example: Creating a Grouped Notification

val notification = NotificationCompat.Builder(context, CHANNEL_ID)
    .setContentTitle("New Messages")
    .setContentText("You have 3 new messages")
    .setSmallIcon(R.drawable.ic_notification)
    .setGroup("message_group")
    .setGroupSummary(true)
    .build()

Example: Adding Individual Notifications to a Group

val individualNotification = NotificationCompat.Builder(context, CHANNEL_ID)
    .setContentTitle("Message from John")
    .setContentText("Hey, are we still on for lunch?")
    .setSmallIcon(R.drawable.ic_notification)
    .setGroup("message_group")
    .build()

11. Implementing Progress Notifications

Example: Basic Progress Notification

val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
val channelId = "progress_channel"
val channelName = "Progress Notifications"

val channel = NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_DEFAULT)
notificationManager.createNotificationChannel(channel)

val builder = NotificationCompat.Builder(this, channelId)
    .setContentTitle("Download in progress")
    .setContentText("50% complete")
    .setSmallIcon(R.drawable.ic_download)
    .setProgress(100, 50, false)

val notification = builder.build()
notificationManager.notify(1, notification)
Property Description Values
setProgress(int max, int progress, boolean indeterminate) Sets the progress bar in the notification max: Maximum value of progress
progress: Current progress value
indeterminate: Whether to show indeterminate progress
setContentText(String text) Updates the content text of the notification String value for progress status
Note: The max and progress values must be integers. Use setProgress(0, 0, true) for indeterminate progress.

Example: Indeterminate Progress Notification

val builder = NotificationCompat.Builder(this, channelId)
    .setContentTitle("Processing files")
    .setContentText("Please wait...")
    .setSmallIcon(R.drawable.ic_process)
    .setProgress(0, 0, true) // Indeterminate progress

val notification = builder.build()
notificationManager.notify(2, notification)

Example: Updating Progress Notification

val builder = NotificationCompat.Builder(this, channelId)
    .setContentTitle("Downloading file")
    .setContentText("0% complete")
    .setSmallIcon(R.drawable.ic_download)
    .setProgress(100, 0, false)

val notification = builder.build()
notificationManager.notify(3, notification)

// Update progress later
val updateBuilder = NotificationCompat.Builder(this, channelId)
    .setContentTitle("Downloading file")
    .setContentText("25% complete")
    .setSmallIcon(R.drawable.ic_download)
    .setProgress(100, 25, false)

val updatedNotification = updateBuilder.build()
notificationManager.notify(3, updatedNotification)

12. Using Full-Screen Intents

Property Description Values
fullScreenIntent Intent to launch when the notification is tapped Intent
priority Notification priority level PRIORITY_HIGH, PRIORITY_MAX
category Notification category for system handling Notification.CATEGORY_CALL, Notification.CATEGORY_ALARM

Example: Creating a Full-Screen Notification

val fullScreenIntent = Intent(this, FullScreenActivity::class.java)
fullScreenIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK

val pendingIntent = PendingIntent.getActivity(this, 0, fullScreenIntent, PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE)

val notification = NotificationCompat.Builder(this, CHANNEL_ID)
    .setSmallIcon(R.drawable.ic_notification)
    .setContentTitle("Incoming Call")
    .setContentText("Tap to answer")
    .setPriority(NotificationCompat.PRIORITY_HIGH)
    .setCategory(NotificationCompat.CATEGORY_CALL)
    .setFullScreenIntent(pendingIntent, true)
    .build()

NotificationManagerCompat.from(this).notify(1, notification)
Note: Full-screen intents require the android.permission.SYSTEM_ALERT_WINDOW permission on Android 6.0 and above.
Warning: Full-screen notifications can disrupt the user experience and should be used sparingly.

Was this article helpful?