テストがてらに主に公式リファレンスの内容を参考に通知表示を実装してみました。
https://developer.android.com/training/notify-user/build-notification
val notificationId = 123
val notificationManager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager
val name = "name"
val descriptionText = "description"
val channel = NotificationChannel("test", name, NotificationManager.IMPORTANCE_HIGH).apply {
description = descriptionText
}
notificationManager.createNotificationChannel(channel)
val notification = NotificationCompat.Builder(this, "CHANNEL_ID")
.setContentTitle("title")
.setContentText("text")
.setSmallIcon(R.drawable.ic_launcher_foreground)
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.build()
notificationManager.notify(notificationId, notification)
上の実装だと通知が表示されませんでした。何が原因なのかある程度悩んで分かったのはテスト用に適当に設定していたNotificationChannelの第一引数の値("test")と、NotificationCompat.Builderの第二引数の値("CHANNEL_ID")が一致していないからでした。
val notificationId = 123
val channelId = "CHANNEL_ID" // これの話
val notificationManager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager
val name = "name"
val descriptionText = "description"
val channel = NotificationChannel(channelId, name, NotificationManager.IMPORTANCE_HIGH).apply {
description = descriptionText
}
notificationManager.createNotificationChannel(channel)
val notification = NotificationCompat.Builder(this, channelId)
.setContentTitle("title")
.setContentText("text")
.setSmallIcon(R.drawable.ic_launcher_foreground)
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.build()
notificationManager.notify(notificationId, notification)
■テスト環境
Pixel 5a (Android12)