2014-09-25 126 views
0

我有一個應用程序可以在使用TimePicker(24小時模式)指定的特定時間設置鬧鐘。Android AlarmManager設置第二天的鬧鐘

我注意到,如果時間是例如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(); 
} 

正如你所看到的應用程序,計算時間差,如果它是負它設置爲第二天報警。這造成了上述的錯誤。如何解決它?

問候,

馬庫斯

回答

0

我已經儘管面臨着同樣的問題,我設法改變我的做法,而是採用

customCalendar.set(Calendar.HOUR_OF_DAY, hour); 
customCalendar.set(Calendar.MINUTE, minute); 
customCalendar.set(Calendar.SECOND, 0); 
customCalendar.set(Calendar.MILLISECOND, 0); 

我改成了

customCalendar.setTimeInMillis(System.currentTimeMillis()); 
customCalendar.add(Calendar.HOUR_OF_DAY, diffHours); 
customCalendar.add(Calendar.MINUTE, diffMinutes); 
customCalendar.set(Calendar.SECOND, 0); 
customCalendar.set(Calendar.MILLISECOND, 0); 

得到diffHoursdiffMinutes這樣

diffHours = timeDifference/(60 * 60 * 1000) % 24; 
diffMinutes = timeDifference/(60 * 1000) % 60; 

如果用戶選擇了相同的當前時間,而不是一個過去的日期或將來的日期,這意味着他要被解僱報警24小時後這樣:

if (timeDifference == 0) { 
    diffHours = 24; 
} 

如果我還想管理幾天?執行此

diffDays = timeDifference/(24 * 60 * 60 * 1000); 

然後轉換幾天縮短到幾小時這樣

if (diffDays != 0) { 
    diffHours = diffHours + (diffDays * 24); 
} 

也能改變你:

if (timeDifference < 0) { 
    timeInMs += 86400000; 
} 

到:

if (timeDifference < 0) { 
    timeDifference += 86400000; 
} 

而且你:

am.set(AlarmManager.RTC_WAKEUP, timeInMs, action); 

要:

am.set(AlarmManager.RTC_WAKEUP, customCalendar.getTimeInMillis(), action);