2017-05-15 28 views
0

我想每天在用戶選擇的特定時間觸發通知,如6'/ 7'/ 8'。AlarmsManager隨時觸發

爲此,我創建了一個WakefulBroadcastReceiver,傳遞給IntentService以創建通知。

這就是我如何設置我的AlarmsManager。 timeInHours是一個整數作爲參數傳遞,6至12:

Intent i = new Intent(context, StepCountNotifyBroadcast.class); 
    PendingIntent pi = PendingIntent.getBroadcast(context, 0, i, 0); 

    // Get the next day at timeInHours hours'. 
    Calendar cal = Calendar.getInstance(); 
    cal.setTime(new Date()); // compute start of the day for the timestamp 
    cal.set(Calendar.HOUR_OF_DAY, timeInHours); 
    cal.set(Calendar.MINUTE, 0); 
    cal.set(Calendar.SECOND, 0); 
    cal.set(Calendar.MILLISECOND, 0); 
    cal.set(Calendar.AM_PM, Calendar.AM); 

    if (new Date().getTime() > cal.getTime().getTime()) 
     cal.add(Calendar.DAY_OF_YEAR, 1); 

    long nextDay = cal.getTime().getTime(); 

    // Setup the alarm. 
    long timeBetween = AlarmManager.INTERVAL_DAY;  // Each day. 
    AlarmManager alarms = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); 
    alarms.cancel(pi); 
    alarms.setRepeating(AlarmManager.RTC_WAKEUP, nextDay, timeBetween, pi); 

    Date nextDayAsDate = new Date(nextDay); 
    GLog.d("AlarmUtils", "scheduleNotifiation for next date: " + nextDayAsDate.toString()); 

它運作良好的時間的50%,但仍然做瘋狂的事情一樣......觸發通知凌晨2:00?! 我知道系統不會在我想要的特定時間觸發通知,這沒關係。但是我們在這裏談論大約18個小時之後。

在日誌中,似乎我的IntentService代碼在某些情況下在半夜有效運行。所以這不是通知本身的問題。

我可以把這個信號切換:

alarms.setRepeating(AlarmManager.RTC_WAKEUP, nextDay, timeBetween, pi); 

到另一行代碼:

alarms.setExact(AlarmManager.RTC_WAKEUP, nextDay, pi); 

但是,這不利於電池的壽命恐怕。

現在我的問題:

  • 有人能告訴我有關的方式Android設備的原因與AlarmsManager的作品?
  • 您是否找到另一種解決方案,而不是耗盡電池壽命,並確保通知將在最多2或3小時後觸發?
  • 在這種特殊情況下,您是否有任何想法進行調試和代碼測試,而無需等待一兩天才能檢測到問題?

在此先感謝。

回答