首页 > 解决方案 > 通知未在android中发送

问题描述

我在这个问题上卡了很久,不知道哪里出了问题。我正在使用广播接收器发送预定的通知。我已经验证了广播接收器的 onReceive() 方法正在相应地被触发,它只是没有被发送的通知。

class AlertReceiver() : BroadcastReceiver() {
@RequiresApi(Build.VERSION_CODES.O)
override fun onReceive(context: Context?, intent: Intent?){
    val notificationChannel =
        NotificationChannel("My Channel", "My Channel", NotificationManager.IMPORTANCE_DEFAULT).apply {
            description = "Sends Alarms"
        }
    val builder = NotificationCompat.Builder(context!!, "My Channel")
        .setSmallIcon(R.drawable.ic_launcher_foreground)
        .setContentTitle("Alarm is ringing")
        .setContentText("Alarm is working")
    with(NotificationManagerCompat.from(context)){
        // Verification that onReceive is firing
        Toast.makeText(context, "Alarm is supposed to ring", Toast.LENGTH_SHORT).show()
        notify(1, builder.build())
    }
}

}

我还在另一个练习应用程序中使用了完全相同的代码,并且得到了预期的行为,所以我认为它与 build.gradle 文件或 android 清单有关。这个问题已经困扰我好几天了,所以我将不胜感激任何解决方案

标签: androidkotlinnotificationsandroid-notifications

解决方案


除了创建NotificationChannel对象之外,还要在应用程序系统设置中注册它createNotificationChannel

with(NotificationManagerCompat.from(context)){
    createNotificationChannel(notificationChannel) // in here!
    // Verification that onReceive is firing
    Toast.makeText(context, "Alarm is supposed to ring", Toast.LENGTH_SHORT).show()
    notify(1, builder.build())
}

之后尝试发布通知

PS。对建设者也有一些小的改进

NotificationCompat.Builder(context!!, notificationChannel.getId())

推荐阅读