通知是 Android 应用与用户交互的重要方式。本文将深入讲解如何在 Compose 应用中正确使用通知系统。
一、创建通知渠道
val channel = NotificationChannel(
"messages",
"消息通知",
NotificationManager.IMPORTANCE_HIGH
)
notificationManager.createNotificationChannel(channel)
二、发送通知
val notification = NotificationCompat.Builder(context, "messages")
.setSmallIcon(R.drawable.ic_notification)
.setContentTitle(title)
.setContentText(message)
.setContentIntent(pendingIntent)
.setAutoCancel(true)
.build()
notificationManager.notify(id, notification)
三、PendingIntent
val pendingIntent = PendingIntent.getActivity(
context,
0,
intent,
PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT
)
四、最佳实践
- ✅ Android 13+ 请求通知权限
- ✅ 创建合适的通知渠道
- ✅ 使用 FLAG_IMMUTABLE
- ✅ 使用 Deep Link 处理点击
- ✅ 分组相关通知
总结
- NotificationChannel:Android 8+ 必须
- NotificationCompat:兼容不同版本
- PendingIntent:处理点击
- Deep Link:与 Navigation 集成