引導

2013-08-16 25 views
0
後AlarmManager設置時間

我嘗試添加「提醒」功能,我的應用程序,讓類似「提醒我日報」,「提醒我每週」選項的用戶選擇,等等引導

所以我剛剛創建了一個鬧鐘:

Intent notificationIntent = new Intent(this, BQBroadcastReceiver.class); 
     PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, notificationIntent, 0); 
     AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE); 
     alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, 
       System.currentTimeMillis() + 24HOURS, 
       24HOURS, 
       pendingIntent); 

目前爲止這麼好。但是如果用戶重新啓動手機會發生什麼?所有警報將在重新啓動時被刪除。我已經有一個BootBroadcastReveicer來重新啓動鬧鐘,但是我要在重新啓動之後設置鬧鐘時間段?

假設用戶將鬧鈴設置爲「在1天內提醒我」。然後報警設置爲24小時。但用戶在23小時後重新啓動手機。然後我的BootBroadcastReceiver在24小時內設置了另一個警報。但我需要它在1小時內,而不是!

我該如何解決這個問題?是否必須經常檢查鬧鐘上剩餘的時間,並不斷將其寫入我的sharedPreferences中,以便重新啓動後能夠重新創建剩餘時間?似乎不是一個好方法。

任何想法?

回答

0

您只需計算通知在您的BootBroatcastReceiver之內發生的剩餘時間。

例如

private long getNextNotificationTime() { 
    long value = // calculate milliseconds until next notification 
    return value; 
} 

現在,在接收器中使用此值。

long nextAlarmTime = this.getNextNotificationTime(); 

Intent notificationIntent = new Intent(this, BQBroadcastReceiver.class); 
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, notificationIntent, 0); 
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE); 
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, 
       nextAlarmTime, 
       24HOURS, 
       pendingIntent); 

這意味着您的鬧鐘只需要在啓動時重新計算,然後每24小時啓動一次。

+0

如何計算nextAlarmTime? BootBroadcastReceiver應該如何知道在報警之前還剩多少? getNextNoticationTime()必須詢問AlarmManager剩下多少,直到報警?如果是的話,多久?每一分鐘?這不是太浪費嗎?每隔一小時?如果用戶在最後一次檢查59分鐘後重新啓動電話,則該警報將關閉59分鐘。 是否有API讓我在關機時喚醒我的應用程序,以便我可以重新計算它? – RazorHail

+0

AlarmManager在啓動時不會知道您的鬧鐘。您需要自己計算BootReceiver中的鬧鐘,並在那裏設置重複鬧鐘。 – Kirk

0
public long setAlarm(int id, int AlermHour, int AlermMinute,String title, String detail) { 
     Intent intent = new Intent(c, OnetimeAlarmReceiver.class); 
     intent.setData(Uri.parse("timer:" + id)); 
     intent.putExtra("title", title); 
     intent.putExtra("detail", detail); 

     AlarmManager alarmMgr0 = (AlarmManager)c.getSystemService(Context.ALARM_SERVICE); 

     PendingIntent pendingIntent0 = PendingIntent.getBroadcast(c, id, intent, 0); 
     Calendar timeOff9 = Calendar.getInstance(); 
     timeOff9.set(Calendar.HOUR_OF_DAY, AlermHour); 
     timeOff9.set(Calendar.MINUTE, AlermMinute); 
     timeOff9.set(Calendar.SECOND, 0); 
     long _alarm = 0; 
     if(timeOff9.getTimeInMillis() <= System.currentTimeMillis()) 
      _alarm = timeOff9.getTimeInMillis() + (AlarmManager.INTERVAL_DAY+1); 
     else 
      _alarm = timeOff9.getTimeInMillis(); 

      alarmMgr0.setRepeating(AlarmManager.RTC_WAKEUP, _alarm,24*60*60*1000,pendingIntent0); 

      return _alarm; 



    } 

使用此方法並使用Alarm Hour,Alarm Min來設置鬧鐘時間。它會自動設置你的時間,而不是計算剩餘時間。