Search code examples
androidkotlinnotificationsandroid-notifications

Notification is not being sent in android


I have been stuck on this problem for a very long time, and I don't know what is wrong. I am using a broadcast receiver to send a scheduled notifications. I have verified that the onReceive() method of the Broadcast Receiver is being fired accordingly, it is just the notification that is not being sent.

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())
    }
}

}

I also used the exact same code in another practice app and I got the intended behavior, so I think it has something to do with the build.gradle file or android manifest. This problem has been bugging me for days so I would appreciate any solutions


Solution

  • besides creating NotificationChannel object also register it in app system-settings with 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())
    }
    

    after that try to post notification

    PS. also some small improvement for builder

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