Local notifications, push notifications (FCM), notification channels, and advanced features.
Notifications Overview
# Dependencies
implementation("androidx.core:core-ktx:1.12.0")
implementation("com.google.firebase:firebase-messaging-ktx:23.4.0")
implementation("androidx.work:work-runtime-ktx:2.9.0") // For scheduled notificationsNotification Channels (Android 8.0+)
class NotificationChannelManager @Inject constructor(
@ApplicationContext private val context: Context
) {
private val notificationManager = context.getSystemService(NotificationManager::class.java)
init {
createChannels()
}
private fun createChannels() {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) return
// Default channel
createChannel(
id = "default",
name = "General",
description = "General notifications",
importance = NotificationManager.IMPORTANCE_DEFAULT
)
// High priority
createChannel(
id = "high_priority",
name = "Important",
description = "Important alerts",
importance = NotificationManager.IMPORTANCE_HIGH
)
// Low priority
createChannel(
id = "low_priority",
name = "Updates",
description = "Background updates",
importance = NotificationManager.IMPORTANCE_LOW
)
// Messaging
createChannel(
id = "messaging",
name = "Messages",
description = "Chat messages",
importance = NotificationManager.IMPORTANCE_HIGH
).apply {
setConversationId("chat", true)
}
// Media
createChannel(
id = "media",
name = "Media Playback",
description = "Music/podcast controls",
importance = NotificationManager.IMPORTANCE_LOW
).apply {
setMediaDescription(MediaDescriptionCompat.Builder()
.setMediaId("media")
.build()
)
}
}
@TargetApi(Build.VERSION_CODES.O)
private fun createChannel(
id: String,
name: String,
description: String,
importance: Int
): NotificationChannel {
val channel = NotificationChannel(id, name, importance).apply {
this.description = description
enableLights(true)
enableVibration(true)
setShowBadge(true)
lockscreenVisibility = Notification.VISIBILITY_PUBLIC
}
notificationManager.createNotificationChannel(channel)
return channel
}
}Basic Notifications
class NotificationHelper @Inject constructor(
@ApplicationContext private val context: Context,
private val channelManager: NotificationChannelManager
) {
private val notificationManager = NotificationManagerCompat.from(context)
// Simple notification
fun showSimpleNotification(
title: String,
message: String,
channelId: String = "default",
notificationId: Int = 1,
pendingIntent: PendingIntent? = null
) {
val builder = NotificationCompat.Builder(context, channelId)
.setSmallIcon(R.drawable.ic_notification)
.setContentTitle(title)
.setContentText(message)
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setAutoCancel(true)
pendingIntent?.let { builder.setContentIntent(it) }
notificationManager.notify(notificationId, builder.build())
}
// Expanded notification
fun showExpandedNotification(
title: String,
message: String,
bigText: String,
channelId: String = "default",
notificationId: Int = 2
) {
val builder = NotificationCompat.Builder(context, channelId)
.setSmallIcon(R.drawable.ic_notification)
.setContentTitle(title)
.setContentText(message)
.setStyle(NotificationCompat.BigTextStyle().bigText(bigText))
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setAutoCancel(true)
notificationManager.notify(notificationId, builder.build())
}
// Image notification
fun showImageNotification(
title: String,
message: String,
imageUrl: String,
channelId: String = "default",
notificationId: Int = 3
) {
// Load image asynchronously
CoroutineScope(Dispatchers.IO).launch {
val bitmap = loadImageFromUrl(imageUrl)
withContext(Dispatchers.Main) {
val builder = NotificationCompat.Builder(context, channelId)
.setSmallIcon(R.drawable.ic_notification)
.setContentTitle(title)
.setContentText(message)
.setStyle(NotificationCompat.BigPictureStyle().bigPicture(bitmap))
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setAutoCancel(true)
notificationManager.notify(notificationId, builder.build())
}
}
}
// Progress notification
fun showProgressNotification(
title: String,
progress: Int,
max: Int = 100,
channelId: String = "default",
notificationId: Int = 4
) {
val builder = NotificationCompat.Builder(context, channelId)
.setSmallIcon(R.drawable.ic_notification)
.setContentTitle(title)
.setContentText("$progress%")
.setProgress(max, progress, false)
.setPriority(NotificationCompat.PRIORITY_LOW)
.setOngoing(true)
notificationManager.notify(notificationId, builder.build())
}
// Action buttons
fun showActionNotification(
title: String,
message: String,
actions: List<NotificationAction>,
channelId: String = "default",
notificationId: Int = 5
) {
val builder = NotificationCompat.Builder(context, channelId)
.setSmallIcon(R.drawable.ic_notification)
.setContentTitle(title)
.setContentText(message)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setAutoCancel(true)
actions.forEach { action ->
builder.addAction(
action.icon,
action.title,
action.pendingIntent
)
}
notificationManager.notify(notificationId, builder.build())
}
// Notification with reply action (Direct Reply)
fun showReplyNotification(
title: String,
message: String,
replyAction: PendingIntent,
channelId: String = "messaging",
notificationId: Int = 6
) {
val replyLabel = context.getString(R.string.reply_label)
val remoteInput = RemoteInput.Builder(KEY_TEXT_REPLY)
.setLabel(replyLabel)
.build()
val action = NotificationCompat.Action.Builder(
R.drawable.ic_reply,
"Reply",
replyAction
)
.addRemoteInput(remoteInput)
.setAllowGeneratedReplies(true)
.build()
val builder = NotificationCompat.Builder(context, channelId)
.setSmallIcon(R.drawable.ic_notification)
.setContentTitle(title)
.setContentText(message)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.addAction(action)
.setAutoCancel(true)
notificationManager.notify(notificationId, builder.build())
}
companion object {
const val KEY_TEXT_REPLY = "key_text_reply"
}
}
data class NotificationAction(
val icon: Int,
val title: String,
val pendingIntent: PendingIntent
)Media Notifications
class MediaNotificationHelper @Inject constructor(
@ApplicationContext private val context: Context
) {
private val notificationManager = NotificationManagerCompat.from(context)
private val mediaSession: MediaSessionCompat
init {
mediaSession = MediaSessionCompat(context, "MediaSession")
mediaSession.setFlags(
MediaSessionCompat.FLAG_HANDLES_MEDIA_BUTTONS or
MediaSessionCompat.FLAG_HANDLES_TRANSPORT_CONTROLS
)
}
fun showMediaNotification(
metadata: MediaMetadataCompat,
playbackState: PlaybackStateCompat
) {
val builder = NotificationCompat.MediaStyle(context, mediaSession.sessionToken)
.setShowActionsInCompactView(0, 1, 2) // Play, Pause, Next
.setMediaSession(mediaSession.sessionToken)
val notification = NotificationCompat.Builder(context, "media")
.setSmallIcon(R.drawable.ic_music_note)
.setContentTitle(metadata.getString(MediaMetadataCompat.METADATA_KEY_TITLE))
.setContentText(metadata.getString(MediaMetadataCompat.METADATA_KEY_ARTIST))
.setLargeIcon(
metadata.getBitmap(MediaMetadataCompat.METADATA_KEY_ALBUM_ART)
)
.setStyle(builder)
.setPriority(NotificationCompat.PRIORITY_LOW)
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
.setOngoing(playbackState.state == PlaybackStateCompat.STATE_PLAYING)
.build()
notificationManager.notify(100, notification)
}
fun updatePlaybackState(state: PlaybackStateCompat) {
mediaSession.setPlaybackState(state)
}
fun updateMetadata(metadata: MediaMetadataCompat) {
mediaSession.setMetadata(metadata)
}
}Scheduled Notifications with WorkManager
class ScheduledNotificationWorker @AssistedInject constructor(
@Assisted context: Context,
@Assisted params: WorkerParameters,
private val notificationHelper: NotificationHelper
) : CoroutineWorker(context, params) {
override suspend fun doWork(): Result {
val title = inputData.getString("title") ?: ""
val message = inputData.getString("message") ?: ""
val channelId = inputData.getString("channel_id") ?: "default"
val notificationId = inputData.getInt("notification_id", 1)
notificationHelper.showSimpleNotification(
title = title,
message = message,
channelId = channelId,
notificationId = notificationId
)
return Result.success()
}
}
// Schedule one-time notification
fun scheduleNotification(
context: Context,
title: String,
message: String,
delay: Long,
timeUnit: TimeUnit = TimeUnit.MILLISECONDS
) {
val workRequest = OneTimeWorkRequestBuilder<ScheduledNotificationWorker>()
.setInputData(workDataOf(
"title" to title,
"message" to message,
"channel_id" to "default",
"notification_id" to Random.nextInt()
))
.setInitialDelay(delay, timeUnit)
.build()
WorkManager.getInstance(context).enqueue(workRequest)
}
// Schedule periodic notification
fun schedulePeriodicNotification(
context: Context,
title: String,
message: String,
interval: Long = 15,
timeUnit: TimeUnit = TimeUnit.MINUTES
) {
val workRequest = PeriodicWorkRequestBuilder<ScheduledNotificationWorker>(interval, timeUnit)
.setInputData(workDataOf(
"title" to title,
"message" to message,
"channel_id" to "default",
"notification_id" to 999
))
.build()
WorkManager.getInstance(context).enqueueUniquePeriodicWork(
"periodic_notification",
ExistingPeriodicWorkPolicy.REPLACE,
workRequest
)
}FCM (Firebase Cloud Messaging)
// Service for handling FCM messages
class MyFirebaseMessagingService : FirebaseMessagingService() {
override fun onMessageReceived(remoteMessage: RemoteMessage) {
super.onMessageReceived(remoteMessage)
// Handle data message
remoteMessage.data.let { data ->
val type = data["type"] ?: "default"
val title = data["title"] ?: "New Message"
val body = data["body"] ?: ""
when (type) {
"chat" -> showChatNotification(title, body, data)
"promo" -> showPromoNotification(title, body, data)
else -> showDefaultNotification(title, body)
}
}
// Handle notification payload (when app in background)
remoteMessage.notification?.let { notification ->
showDefaultNotification(notification.title!!, notification.body!!)
}
}
override fun onNewToken(token: String) {
super.onNewToken(token)
// Send token to your server
sendTokenToServer(token)
}
private fun showDefaultNotification(title: String, body: String) {
val intent = Intent(this, MainActivity::class.java)
.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
val pendingIntent = PendingIntent.getActivity(
this, 0, intent,
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
)
val builder = NotificationCompat.Builder(this, "high_priority")
.setSmallIcon(R.drawable.ic_notification)
.setContentTitle(title)
.setContentText(body)
.setAutoCancel(true)
.setContentIntent(pendingIntent)
.setPriority(NotificationCompat.PRIORITY_HIGH)
NotificationManagerCompat.from(this).notify(
System.currentTimeMillis().toInt(), builder.build()
)
}
private fun showChatNotification(title: String, body: String, data: Map<String, String>) {
val chatId = data["chat_id"] ?: ""
val intent = Intent(this, ChatActivity::class.java).apply {
putExtra("chat_id", chatId)
addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
}
val pendingIntent = PendingIntent.getActivity(
this, chatId.hashCode(), intent,
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
)
// Direct reply action
val replyIntent = Intent(this, ReplyReceiver::class.java).apply {
putExtra("chat_id", chatId)
}
val replyPendingIntent = PendingIntent.getBroadcast(
this, chatId.hashCode(), replyIntent,
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
)
val remoteInput = RemoteInput.Builder(NotificationHelper.KEY_TEXT_REPLY)
.setLabel("Reply")
.build()
val replyAction = NotificationCompat.Action.Builder(
R.drawable.ic_reply, "Reply", replyPendingIntent
)
.addRemoteInput(remoteInput)
.setAllowGeneratedReplies(true)
.build()
val builder = NotificationCompat.Builder(this, "messaging")
.setSmallIcon(R.drawable.ic_chat)
.setContentTitle(title)
.setContentText(body)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setCategory(NotificationCompat.CATEGORY_MESSAGE)
.setContentIntent(pendingIntent)
.addAction(replyAction)
.setAutoCancel(true)
NotificationManagerCompat.from(this).notify(
chatId.hashCode(), builder.build()
)
}
}
// Manifest registration
/*
<service
android:name=".MyFirebaseMessagingService"
android:exported="false">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
*/FCM Token Management
class FCMTokenManager @Inject constructor(
@ApplicationContext private val context: Context,
private val apiService: ApiService,
private val dataStore: DataStore<Preferences>
) {
companion object {
val FCM_TOKEN = stringPreferencesKey("fcm_token")
val TOKEN_SENT_TO_SERVER = booleanPreferencesKey("token_sent_to_server")
}
suspend fun getToken(): String? {
return try {
FirebaseMessaging.getInstance().token.await()
} catch (e: Exception) {
null
}
}
suspend fun registerToken() {
val token = getToken() ?: return
val sent = dataStore.data.first()[TOKEN_SENT_TO_SERVER] ?: false
if (sent) return
// Send to server
apiService.registerDeviceToken(token)
.onSuccess {
dataStore.edit { it[TOKEN_SENT_TO_SERVER] = true }
}
}
fun observeTokenChanges() = FirebaseMessaging.getInstance().tokenChanges
.onEach { token ->
// Token refreshed, send to server
CoroutineScope(Dispatchers.IO).launch {
apiService.registerDeviceToken(token).onSuccess {
dataStore.edit { it[TOKEN_SENT_TO_SERVER] = true }
}
}
}
.launchIn(CoroutineScope(Dispatchers.Main))
}Notification Permissions (Android 13+)
class NotificationPermissionManager(
private val activity: ComponentActivity
) {
private val permissionLauncher = activity.registerForActivityResult(
ActivityResultContracts.RequestPermission()
) { granted ->
if (granted) {
// Permission granted
}
}
fun requestPermission() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
if (ContextCompat.checkSelfPermission(
activity, Manifest.permission.POST_NOTIFICATIONS
) != PackageManager.PERMISSION_GRANTED
) {
permissionLauncher.launch(Manifest.permission.POST_NOTIFICATIONS)
}
}
}
fun areNotificationsEnabled(): Boolean {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) return true
val notificationManager = activity.getSystemService(NotificationManager::class.java)
return notificationManager.areNotificationsEnabled()
}
}Grouping Notifications
// Group notifications
fun showGroupedNotifications(context: Context, messages: List<Message>) {
val groupKey = "group_messages"
// Summary notification
val summaryBuilder = NotificationCompat.Builder(context, "messaging")
.setSmallIcon(R.drawable.ic_chat)
.setContentTitle("${messages.size} new messages")
.setStyle(NotificationCompat.InboxStyle()
.setBigContentTitle("${messages.size} new messages")
.setSummaryText("Tap to view all")
)
.setGroup(groupKey)
.setGroupSummary(true)
.setPriority(NotificationCompat.PRIORITY_LOW)
NotificationManagerCompat.from(context).notify(0, summaryBuilder.build())
// Individual notifications
messages.forEachIndexed { index, message ->
val builder = NotificationCompat.Builder(context, "messaging")
.setSmallIcon(R.drawable.ic_chat)
.setContentTitle(message.sender)
.setContentText(message.text)
.setGroup(groupKey)
.setGroupSummary(false)
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
NotificationManagerCompat.from(context).notify(
message.id.hashCode(), builder.build()
)
}
}Try It
Create notification channels. Show simple, expanded, image, progress notifications. Add action buttons. Implement Direct Reply. Set up FCM service. Schedule with WorkManager.
# Add to build.gradle.kts:
# implementation("com.google.firebase:firebase-messaging-ktx:23.4.0")Notifications mastery
- Create notification channels with different priorities
- Show basic, BigText, BigPicture, InboxStyle notifications
- Add action buttons with PendingIntents
- Implement Direct Reply with RemoteInput
- Build media playback notification
- Schedule notifications with WorkManager
- Set up FCM service for push notifications
- Handle token registration and refresh
- Request POST_NOTIFICATIONS permission (Android 13+)
- Group notifications with summary
NotificationChannel required for Android 8+. Use NotificationCompat.Builder. Channels: importance, lights, vibration, badges. Styles: BigText, BigPicture, Inbox, Media. Actions: PendingIntent + RemoteInput for reply. FCM for push. WorkManager for scheduling. POST_NOTIFICATIONS permission on Android 13+.
Resources
- Notifications: https://developer.android.com/develop/ui/views/notifications
- FCM: https://firebase.google.com/docs/cloud-messaging/android/client
- Notification Channels: https://developer.android.com/training/notify-user/channels
- Media Notifications: https://developer.android.com/media/building-apps/notification