I am trying to set an alarm to fire everyday at specific time ex: 8:00am but alarm manager not fire at exact time sometime after 2 minute of specific time and sometime more than that .
My code
class AlarmReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
val builder = NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.ic_stat_name)
.setContentTitle("notification title")
.setContentInfo("info")
.setDefaults(NotificationCompat.DEFAULT_SOUND)
val notifManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notifManager.notify(0, builder.build())
}
companion object {
fun startAlarmManager(context: Context, hour: Int, minute: Int = 0) {
// set time for alarm manager
val calendar = Calendar.getInstance()
calendar.timeInMillis = System.currentTimeMillis()
calendar.set(Calendar.HOUR_OF_DAY, hour)
calendar.set(Calendar.MINUTE, minute)
calendar.set(Calendar.SECOND, 0)
calendar.set(Calendar.MILLISECOND, 0)
if (calendar.timeInMillis < System.currentTimeMillis())
calendar.timeInMillis += 1000 * 60 * 60 * 24
// set up alarm manager
val alarmReceiver = Intent(context, AlarmReceiver::class.java)
val pendingIntent = PendingIntent.getBroadcast(context, 0, alarmReceiver, PendingIntent.FLAG_UPDATE_CURRENT)
val alarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.timeInMillis, AlarmManager.INTERVAL_DAY,
pendingIntent)
context.toast("started")
}
fun stopAlarmManager(context: Context) {
// set up alarm manager
val alarmReceiver = Intent(context, AlarmReceiver::class.java)
val pendingIntent = PendingIntent.getBroadcast(context, 0, alarmReceiver, 0)
val alarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
alarmManager.cancel(pendingIntent)
}
}
}
when i use
alarmManager.setExact(AlarmManager.RTC_WAKEUP, calendar.timeInMillis,pendingIntent)
It work fine and notification send exact at specific time One more thing, I have already read this question but not solve my problem .
Using Alarmmanager to start a service at specific time
Alarm Manager not working at specific given time interval
and also