首页 > 解决方案 > API 29 上未显示 Android 通知

问题描述

我在 Android API 29 上显示通知时遇到问题。虽然代码基于教程,但执行代码时不会显示通知。

MainActivity.kt:

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        ...

        val notification =
            NotificationCompat.Builder(this, NOTIFICATION_GROUP_LOCATION)
                .setContentTitle("NoteIfication")
                .setContentText("Note:  Priority: ")
                .setSmallIcon(R.drawable.ic_notifications_black_24dp)
                .setPriority(NotificationCompat.PRIORITY_DEFAULT)
                .build()
        val channel = NotificationChannel(
            NOTIFICATION_CHANNEL_LOCATION,
            "group location",
            NotificationManager.IMPORTANCE_DEFAULT
        ).apply {
            description = "notification channel for note reminders in app HyperNote"
        }

        val notificationManager =
            getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        notificationManager.createNotificationChannel(channel)

        with(NotificationManagerCompat.from(this)) {
            notify(2134, notification)
        }
    }

}

标签: androidkotlinandroid-notifications

解决方案


正如 Mike M. 指出的:“看起来您可能使用了两个不同的频道 ID;NOTIFICATION_GROUP_LOCATION 和 NOTIFICATION_CHANNEL_LOCATION。您在 NotificationCompat.Builder(this, ...) 中传递的 ID 必须与在 NotificationChannel 中传递的 ID 相同(...,“组位置”,IMPORTANCE_DEFAULT)。”

更改 ID 后,将显示通知。


推荐阅读