Search code examples
androidalarmmanager

AlarmManager setRepeating() fires at incorrect time


I am trying to get AlarmManager to fire at 8AM in the morning but the issue is that when I run this app at 21:00 (or any other time) it launches my NotificationService class that shows the notification at the current time and not in the morning as defined.

val alarmManager:AlarmManager? = getSystemService(Context.ALARM_SERVICE) as AlarmManager
val firingCal:Calendar = Calendar.getInstance().apply {
            set(Calendar.HOUR_OF_DAY,8)
            set(Calendar.MINUTE,0)
            set(Calendar.SECOND,0)
        }

        val serviceIntent: Intent = Intent(this,NotificationService::class.java)
        val mPendingIntent = PendingIntent.getService(this,123, serviceIntent, PendingIntent.FLAG_UPDATE_CURRENT)
        alarmManager?.setRepeating(AlarmManager.RTC, firingCal.timeInMillis, AlarmManager.INTERVAL_DAY, mPendingIntent);

Solution

  • The problem is this

    val firingCal:Calendar = Calendar.getInstance().apply {
            set(Calendar.HOUR_OF_DAY,8)
            set(Calendar.MINUTE,0)
            set(Calendar.SECOND,0)
     }
    

    You are setting the time to 8:00, but if it is now past 8:00am, this is now set to the past, so the alarm fires immediately.

    You have to check if the time is past 8:00 and add 1 to your day:

    val firingCal:Calendar = Calendar.getInstance().apply {
            if (get(Calendar.HOUR_OF_DAY) >= 8) {
                add(Calendar.DAY_OF_MONTH, 1)
            }
            set(Calendar.HOUR_OF_DAY,8)
            set(Calendar.MINUTE,0)
            set(Calendar.SECOND,0)
    }