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()
}
}
CodePudding user response:
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)
}