Skip to Content

Notifications trong Android

1. Giới thiệu

Notifications hiển thị thông tin cho user bên ngoài UI của app.

2. Setup

Permission (Android 13+)

<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />

Request Permission

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { if (checkSelfPermission(Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) { requestPermissions(arrayOf(Manifest.permission.POST_NOTIFICATIONS), 100) } }

3. Notification Channel (Android 8+)

private fun createNotificationChannel() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { val channel = NotificationChannel( "messages", "Messages", NotificationManager.IMPORTANCE_HIGH ).apply { description = "Chat message notifications" enableLights(true) lightColor = Color.BLUE enableVibration(true) } val manager = getSystemService(NotificationManager::class.java) manager.createNotificationChannel(channel) } }

Importance Levels

LevelBehavior
IMPORTANCE_HIGHHeads-up
IMPORTANCE_DEFAULTSound
IMPORTANCE_LOWNo sound
IMPORTANCE_MINSilent

4. Basic Notification

fun showNotification(context: Context) { val notification = NotificationCompat.Builder(context, "messages") .setSmallIcon(R.drawable.ic_notification) .setContentTitle("New Message") .setContentText("You have a new message from Alice") .setPriority(NotificationCompat.PRIORITY_HIGH) .setAutoCancel(true) .build() NotificationManagerCompat.from(context).notify(1, notification) }

5. Notification với Action

val intent = Intent(context, ChatActivity::class.java) val pendingIntent = PendingIntent.getActivity( context, 0, intent, PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT ) val replyIntent = PendingIntent.getBroadcast( context, 0, Intent(context, ReplyReceiver::class.java), PendingIntent.FLAG_MUTABLE ) val notification = NotificationCompat.Builder(context, "messages") .setSmallIcon(R.drawable.ic_message) .setContentTitle("New Message") .setContentText("Hello!") .setContentIntent(pendingIntent) .addAction(R.drawable.ic_reply, "Reply", replyIntent) .addAction(R.drawable.ic_mark_read, "Mark as Read", markReadIntent) .build()

6. Big Text/Picture Style

Big Text

val notification = NotificationCompat.Builder(context, "news") .setSmallIcon(R.drawable.ic_news) .setContentTitle("Breaking News") .setContentText("Short preview...") .setStyle( NotificationCompat.BigTextStyle() .bigText("This is a much longer text that will be shown when the notification is expanded...") ) .build()

Big Picture

val notification = NotificationCompat.Builder(context, "photos") .setSmallIcon(R.drawable.ic_photo) .setContentTitle("New Photo") .setStyle( NotificationCompat.BigPictureStyle() .bigPicture(bitmap) .bigLargeIcon(null as Bitmap?) ) .build()

7. Progress Notification

val builder = NotificationCompat.Builder(context, "downloads") .setSmallIcon(R.drawable.ic_download) .setContentTitle("Downloading...") .setPriority(NotificationCompat.PRIORITY_LOW) val notificationManager = NotificationManagerCompat.from(context) // Indeterminate builder.setProgress(0, 0, true) notificationManager.notify(1, builder.build()) // Determinate for (progress in 0..100 step 10) { builder.setProgress(100, progress, false) notificationManager.notify(1, builder.build()) delay(500) } // Complete builder.setContentText("Download complete") .setProgress(0, 0, false) notificationManager.notify(1, builder.build())

8. Messaging Style

val person = Person.Builder().setName("Alice").build() val notification = NotificationCompat.Builder(context, "messages") .setSmallIcon(R.drawable.ic_message) .setStyle( NotificationCompat.MessagingStyle(person) .addMessage("Hi!", System.currentTimeMillis(), person) .addMessage("How are you?", System.currentTimeMillis(), person) ) .build()

9. Direct Reply

val remoteInput = RemoteInput.Builder("key_text_reply") .setLabel("Reply...") .build() val replyAction = NotificationCompat.Action.Builder( R.drawable.ic_reply, "Reply", replyPendingIntent ) .addRemoteInput(remoteInput) .build() val notification = NotificationCompat.Builder(context, "messages") .setSmallIcon(R.drawable.ic_message) .setContentTitle("New Message") .addAction(replyAction) .build() // Receive reply in BroadcastReceiver val reply = RemoteInput.getResultsFromIntent(intent) ?.getCharSequence("key_text_reply") ?.toString()

10. Grouped Notifications

val GROUP_KEY = "com.example.MESSAGES" // Individual notifications messages.forEach { message -> val notification = NotificationCompat.Builder(context, "messages") .setSmallIcon(R.drawable.ic_message) .setContentTitle(message.sender) .setContentText(message.text) .setGroup(GROUP_KEY) .build() notificationManager.notify(message.id, notification) } // Summary notification val summary = NotificationCompat.Builder(context, "messages") .setSmallIcon(R.drawable.ic_message) .setContentTitle("${messages.size} new messages") .setStyle( NotificationCompat.InboxStyle() .addLine("Alice: Hi!") .addLine("Bob: Hello!") .setSummaryText("${messages.size} messages") ) .setGroup(GROUP_KEY) .setGroupSummary(true) .build() notificationManager.notify(0, summary)

11. Cancel Notification

// By ID notificationManager.cancel(notificationId) // All notificationManager.cancelAll()

📝 Tóm tắt

FeatureAPI
ChannelNotificationChannel (Android 8+)
PermissionPOST_NOTIFICATIONS (Android 13+)
BuilderNotificationCompat.Builder
StylesBigTextStyle, BigPictureStyle, MessagingStyle
ActionsaddAction()
GroupssetGroup(), setGroupSummary()
Last updated on