【发布时间】:2014-09-25 11:45:05
【问题描述】:
我有一个应用程序,可以在使用 TimePicker(24 小时模式)指定的特定时间设置闹钟。
我注意到如果时间是例如23:00 并且您将闹钟设置为 01:00,AlarmManager 会将其解释为已过的日期。目前,我将闹钟设置如下:
private void setUpAlarm(int hour, int minute){
long timeInMs = 0;
long currentTimeInMs = 0;
long timeDifference = 0;
// Set up a calendar to calculate when the alarm should go off
Calendar customCalendar = new GregorianCalendar();
customCalendar.set(Calendar.HOUR_OF_DAY, hour);
customCalendar.set(Calendar.MINUTE, minute);
customCalendar.set(Calendar.SECOND, 0);
customCalendar.set(Calendar.MILLISECOND, 0);
Date customDate = customCalendar.getTime();
timeInMs = customDate.getTime();
currentTimeInMs = System.currentTimeMillis();
timeDifference = timeInMs - currentTimeInMs;
/*
* If the user has entered a date that has passed (time difference is negative)
* add 24 hours to the alarm time.
*/
if(timeDifference < 0){
timeInMs += 86400000;
}
//set the alarm
Intent intent = new Intent(this, AlarmClockRingRing.class);
action = PendingIntent.getActivity(this, (int)timeInMs,
intent, 0);
AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
am.set(AlarmManager.RTC_WAKEUP, timeInMs, action);
Toast.makeText(this, "One shot alarm set at " + alarmTime, Toast.LENGTH_LONG).show();
}
如您所见,该应用会计算时差,如果为负数,则会设置第二天的闹钟。这会产生上述错误。如何解决?
问候,
马库斯
【问题讨论】:
标签: android calendar alarmmanager