1
votes

I'm trying to set an alarm with AlarmManager, but my BroadcastReceiver never gets called. Here is my snippet.

    val receiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context, intent: Intent) {
            //Never gets hit
        }
    }
    context.registerReceiver(receiver, IntentFilter(LOCAL_NOTIFICATION))

    val intent = Intent()
    intent.action = LOCAL_NOTIFICATION

    val alarmManager = context.getSystemService(ALARM_SERVICE) as? AlarmManager
    val pendingIntent = PendingIntent.getService(context, 1, intent, PendingIntent.FLAG_UPDATE_CURRENT)

    val calendar = Calendar.getInstance()

    calendar.add(Calendar.SECOND, 10)

    alarmManager?.set(AlarmManager.RTC_WAKEUP, calendar.timeInMillis, pendingIntent)

I've tried registering a broadcast receiver in AndroidManifest.xml but nothing seems to be working.

2

2 Answers

2
votes

I just noticed that I was calling getService() on PendingIntent instead of getBroadcast()

After changing that, it works perfectly!

0
votes

In addition to the preferred answer, I set the class of the intent before it worked. See the example below:

val intent = Intent()
intent.action = LOCAL_NOTIFICATION
intent.setClass(context, MyBroadCastReceiver::class.java) //this line

before passing the intent to the pendintIntent. hope it helps