0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Android 通知が表示されない問題

Posted at

テストがてらに主に公式リファレンスの内容を参考に通知表示を実装してみました。
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)

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?