AlarmManager setRepeating()在不正确的时间触发

时间:2019-05-17 18:25:39

标签: android alarmmanager

我正在尝试让AlarmManager在早上8点启动,但是问题是,当我在21:00(或任何其他时间)运行此应用时,它将启动我的 NotificationService 类,该类显示通知是在当前时间而不是定义的早晨。

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);

1 个答案:

答案 0 :(得分:1)

问题是这个

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

您将时间设置为8:00,但是如果现在是上午8:00,则现在已设置为过去,因此警报会立即触发。

您必须检查时间是否在8:00以后,并在当天加1:

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)
}