2012-12-14 45 views
4

我已經使用下面的代碼來設置每天只有一次alarmmanager,我想有2個不同的時間來設置,所以每天2次。如何每天使用2次alarmmanager?

我的代碼:

Calendar calendar = Calendar.getInstance(); 
calendar.set(Calendar.HOUR_OF_DAY, 10); 
calendar.set(Calendar.MINUTE, 35); 
calendar.set(Calendar.SECOND, 0); AlarmManager am = (AlarmManager)  getApplicationContext().getSystemService (Context.ALARM_SERVICE); 
PendingIntent pi = PendingIntent.getBroadcast(getApplicationContext(), 0, new Intent(getApplicationContext(),  AlarmReceiver.class),  PendingIntent.FLAG_UPDATE_CURRENT); 
am.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),  AlarmManager.INTERVAL_DAY, pi); 

回答

10

您可以使用AlarmManager.INTERVAL_DAY/2的間隔:

Calendar calendar = Calendar.getInstance(); 
calendar.set(Calendar.HOUR_OF_DAY, 10); 
calendar.set(Calendar.MINUTE, 35); 
calendar.set(Calendar.SECOND, 0);  
AlarmManager am = (AlarmManager)getApplicationContext().getSystemService (Context.ALARM_SERVICE); 
Intent intent = new Intent(getApplicationContext(), AlarmReceiver.class); 
PendingIntent pi = PendingIntent.getBroadcast(getApplicationContext(), 0, intent,  PendingIntent.FLAG_UPDATE_CURRENT); 
am.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),  AlarmManager.INTERVAL_DAY/2, pi); 

,但如果在您炒掉報警一天的時間重要的,你可以使用兩個日曆對象:

Calendar cal1 = Calendar.getInstance(); 
cal1.set(Calendar.HOUR_OF_DAY, 12); //midday 
cal1.set(Calendar.MINUTE, 00); 
cal1.set(Calendar.SECOND, 00); 

Calendar cal2 = Calendar.getInstance(); 
cal2.set(Calendar.HOUR_OF_DAY, 18);//8pm for example 
cal2.set(Calendar.MINUTE, 00); 
cal2.set(Calendar.SECOND, 00); 

並設置告警管理:

am.setRepeating(AlarmManager.RTC_WAKEUP, cal1.getTimeInMillis(),cal2.getTimeInMillis(), pi); 
+0

感謝這個優秀的answer.Notification 1是確定的,通知2號:我有一個錯誤:PhoneStatusBar(204):禁用:<擴大圖標警報股票* SYSTEM_INFO回家最近的時鐘> w ^/InputMethodManagerService(149):窗口已經集中,忽略焦點收益:[email protected] attribute = null –

+0

這個問題似乎並不是由設置報警管理器代碼造成的,我建議更改您正在測試的模擬器。 –

+0

我試試!非常感謝! :-D –

-2
void alaramStart() { 
    Calendar cur_cal = Calendar.getInstance(); 
    Intent intent = new Intent(MainActivity.this, MyBRoadcast.class); 
    intent.setAction("HELLO"); 
    PendingIntent pintent = PendingIntent.getService(MainActivity.this, 1234567, intent, 0); 
    AlarmManager alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE); 
    alarm.setRepeating(AlarmManager.RTC_WAKEUP, cur_cal.getTimeInMillis(), 5000, pintent); 
} 
+0

嘿我試過了,它真的有效 –

相關問題