android 后未发送通知

Notification is not being sent in 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 清单有关。这个问题已经困扰我好几天了,所以我很感激任何解决方案

除了创建 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())
}

之后尝试post通知

PS。对构建器也有一些小改进

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