[英]AlarmManager alarm not starting exactly at the change of minute
我正在制作一個鬧鍾,盡管使用了精確的鬧鍾,但它並不是在一分鍾的變化開始的:
例如,我設置為7:30,它將在7:30:00-7:31之間開始(無法檢查確切時間)。
我這樣撥打警報:
// Create the alarm
CustomAlarmManager alarmManager = new CustomAlarmManager(getActivity());
alarmManager.scheduleRepeatingAlarm(getActivity(), alarmID, alarmHour, alarmMinute);
運行此功能以創建警報:
public void scheduleRepeatingAlarm(Context context, int alarmID, int alarmHour, int alarmMinute) {
// Create an intent to go to the notifications reciever class
Intent intent = new Intent(context, AlarmNotificationReciever.class);
// Bundle information and add to the intent for use later
Bundle extras = new Bundle();
extras.putInt("AlarmId", alarmID);
extras.putInt("AlarmHour", alarmHour);
extras.putInt("AlarmMinute", alarmMinute);
intent.putExtras(extras);
// Create a pending intent for the alarm id and intent
PendingIntent pIntent = PendingIntent.getBroadcast(context,
alarmID, intent, PendingIntent.FLAG_CANCEL_CURRENT);
// Create a calender variable with the time for the alarm
Calendar calender = Calendar.getInstance();
calender.set(Calendar.HOUR_OF_DAY, alarmHour);
calender.set(Calendar.MINUTE, alarmMinute);
// Create a variable for the current alarm time
LocalTime currentAlarmTime = LocalTime.parse(alarmHour+":"+alarmMinute+":"+"00");
// Create a variable for the local time
LocalTime localDeviceTime = LocalTime.now();
// If the alarm has already elapsed today add one day to it so it runs for tomorrow
if (localDeviceTime.isAfter(currentAlarmTime)) {
calender.add(Calendar.DATE, 1);
System.out.println("The time of day for the alarm has already past rescheduling for tomorrow");
}
// For the different versions of operating system set off a single shot alarm
if(Build.VERSION.SDK_INT >= 23) {
mAlarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP,
calender.getTimeInMillis(), pIntent);
} else if(Build.VERSION.SDK_INT >= 19) {
mAlarmManager.setExact(AlarmManager.RTC_WAKEUP, calender.getTimeInMillis(), pIntent);
} else {
mAlarmManager.set(AlarmManager.RTC_WAKEUP, calender.getTimeInMillis(), pIntent);
}
}
我假設問題出在這里:
Calendar calender = Calendar.getInstance();
calender.set(Calendar.HOUR_OF_DAY, hour);
calender.set(Calendar.MINUTE, minute);
而在設置警報時此行:
mAlarmManager.setExact(AlarmManager.RTC_WAKEUP, calender.getTimeInMillis(), pIntent);
但是我不確定為什么那不是從分鍾的改變開始的。
謝謝你的幫助
Calendar.getInstance()
返回設置為當前時間(和日期)的Calendar
實例。
您正在設置此Calendar
實例的HOUR_OF_DAY
和MINUTE
字段,但是SECOND
字段仍具有其初始值,這就是這種行為的原因。
更改以下內容:
Calendar calender = Calendar.getInstance();
calender.set(Calendar.HOUR_OF_DAY, hour);
calender.set(Calendar.MINUTE, minute);
對此:
Calendar calender = Calendar.getInstance();
calender.set(Calendar.HOUR_OF_DAY, hour);
calender.set(Calendar.MINUTE, minute);
calendar.set(Calendar.SECOND, 0);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.