Home > front end >  Android notification built on BroadcastReceiver is not showing
Android notification built on BroadcastReceiver is not showing

Time:03-24

I'm trying to push a notification inside a BroadcastReceiver. Up until now the notification doesn't have anything specific on it, I'm really just trying to show it.

I copied the code from https://developer.android.com/training/notify-user/time-sensitive and added the call to the NotificationManager to show the notification, but again, nothing happens.

The BroadcastReceiver:

package codehero.twitteralarmclock.receivers

import android.app.NotificationManager
import android.app.PendingIntent
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.widget.Toast
import androidx.core.app.NotificationCompat
import codehero.twitteralarmclock.R
import codehero.twitteralarmclock.ui.main.snooze.SnoozeActivity

class AlarmBroadcastReceiver : BroadcastReceiver() {
    override fun onReceive(context: Context, intent: Intent) {
        Toast.makeText(context, "Alarm triggered", Toast.LENGTH_LONG).show()

        val fullScreenIntent = Intent(context, SnoozeActivity::class.java)
        intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
        val fullScreenPendingIntent = PendingIntent.getActivity(context, 0, fullScreenIntent, PendingIntent.FLAG_IMMUTABLE)

        val notificationBuilder = NotificationCompat
            .Builder(context, "0")
            .setSmallIcon(R.drawable.ic_launcher_foreground)
            .setContentTitle("Incoming call")
            .setContentText("(919) 555-1234")
            .setPriority(NotificationCompat.PRIORITY_HIGH)
            .setCategory(NotificationCompat.CATEGORY_CALL)
            .setContentIntent(fullScreenPendingIntent)

        val notification = notificationBuilder.build()

        val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        notificationManager.notify(0, notification)
    }
}

The code inside the BroadcastReceiver is running because the Toast gets shown. I don't know if I need anything else, if the notification won't trigger because I'm creating it inside a BroadcastReceiver.

Any help is highly appreciate since all the other answers I found here didn't help.

Thank you for your time!

CodePudding user response:

Starting from Android 8, Creating a notification channel first is necessary. If the notification Channel was nos created first (referred by the CHANNEL_ID), the notification will not show up for Android 8 and upper.

Please check this topic : https://developer.android.com/training/notify-user/build-notification#Priority

  • Related