【发布时间】:2017-11-27 22:21:22
【问题描述】:
我正在安排重复闹钟,每周二早上 08:30 响铃。
因为打瞌睡,我不能使用AlarmManager.setRepeating,因为闹钟的时间不准确(必须准确,我了解对电池的影响)。
所以,我使用这段代码来安排第一个警报:
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.setFirstDayOfWeek(Calendar.WEDNESDAY); // Trick not to get a "tuesday" timestamp in the past if today is wednesday+ !
calendar.set(Calendar.DAY_OF_WEEK, Calendar.TUESDAY);
calendar.set(Calendar.HOUR_OF_DAY, 8);
calendar.set(Calendar.MINUTE, 30);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
long scheduledTime = calendar.getTimeInMillis();
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, scheduledTime, pendingIntent);
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
alarmManager.setExact(AlarmManager.RTC_WAKEUP, scheduledTime, pendingIntent);
} else {
alarmManager.set(AlarmManager.RTC_WAKEUP, scheduledTime, pendingIntent);
}
而且它完美无瑕。
问题是,当我的BroadcastReceiver 在星期二上午 8:30 使用 Intent 时,我必须重新安排闹钟。
但是在星期二 08:30 和星期二 23:59 之间,该方法会给我一个“过去”的时间戳,这是不正确的。
除了“如果提供的时间戳是过去的,添加 1 周”之外,还有什么方法可以解决这个问题吗?
【问题讨论】:
-
抱歉,我不明白为什么您在重新安排闹钟时无法计算下一个安排日期/时间。
-
因为代码的第一部分(第 0 - 8 行)会给我一个现在之前的时间戳?
-
比较
if (calculated.before(now)) {... -
@LewBloch 这就是我目前正在做的事情,但感觉如此不雅,我正在寻找一种更“通用”的方法。
-
“感觉”是一种情感。工程原理是什么?无论如何,您已经将
calendar的初始值设置为当前时间两次,按照工程标准,这是“不雅”的。如果您坚持使用老式的时间操作库,您可以考虑使用 docs.oracle.com/javase/8/docs/api/java/util/… 方法。
标签: java android datetime calendar