skushu
skushu

Reputation: 321

Why is my alarmmanager not going off at specified time?

setAlarm is called everytime I press a button. Everytime I do so, the "test" message comes up 5 seconds afterwards no matter what. Changing the second parameter for .setExact() doesn't seem to affect when the alarm goes off.

set Alarm method in MainActivity

private fun setAlarm (cal : Calendar){
        val alarmManager :AlarmManager = getSystemService(Context.ALARM_SERVICE) as AlarmManager
        val intent = Intent (this, AlertReceiver().javaClass)
        val pendingIntent : PendingIntent = PendingIntent.getBroadcast(this, 1, intent, 0)
        //
        alarmManager.setExact(AlarmManager.RTC_WAKEUP, 100000, pendingIntent)
}

AlertReceiver

class AlertReceiver: BroadcastReceiver() {
    override fun onReceive(context: Context?, intent: Intent?) {
        Toast.makeText(context, "test", Toast.LENGTH_SHORT).show()
    }
}

Upvotes: 1

Views: 223

Answers (1)

Yaqoob Bhatti
Yaqoob Bhatti

Reputation: 1535

You should try this

private fun setAlarm (cal : Calendar){
        val calendar = Calendar.getInstance()
            calendar.apply {
                    set(Calendar.HOUR_OF_DAY, 6)
                    set(Calendar.MINUTE, 30)
                    set(Calendar.SECOND, 0)
                }
                val alarmManager :AlarmManager = getSystemService(Context.ALARM_SERVICE) as AlarmManager
                val intent = Intent (this, AlertReceiver().javaClass)
                val pendingIntent : PendingIntent = PendingIntent.getBroadcast(this, 1, intent, 0)
                //
            
         alarmManager.set(  AlarmManager.RTC_WAKEUP,
                    calendar.timeInMillis,
                    pendingIntent)
        }

Upvotes: 1

Related Questions