2017-06-09 35 views
0

我有一個alarmManager,每天早上9點重複調用服務。我想每天(上午9點用服務A,中午用服務B和下午4點用服務C觸發鬧鐘(重複)。)AlarmManager set重複多個實例

我目前的做法是每3小時重複一次並獲取當前時間在服務中,並根據時間確定應該觸發哪個動作,但這種感覺過於冒險。這是我的代碼。我希望我可以實例化多個AlarmManager實例,但我懷疑我可以給它的初始化方式。

 Intent i_notifcreate = new Intent(this, NotifCreator.class); 
     PendingIntent pi_notifcreator = PendingIntent.getService(this, 0, i_notifcreate, PendingIntent.FLAG_UPDATE_CURRENT); 
     AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE); 
     Calendar calendar = Calendar.getInstance(); 
     calendar.setTimeInMillis(System.currentTimeMillis()); 
     calendar.set(Calendar.HOUR_OF_DAY, 9); 
     calendar.set(Calendar.MINUTE, 00); 
     Log.e("NextAlarm", calendar.getTime().toString()); 
     alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_HOUR, pi_notifcreator); 

pseduocode內部服務

if(time == 9AM){ 
    A() 
} else if (time == noon){ 
    B() 
} ... etc 

回答

0

我可以用這個題目不好的問題alarmmanager 2 times

Calendar cal1 = Calendar.getInstance(); 
cal1.set(Calendar.HOUR_OF_DAY, 05); 
cal1.set(Calendar.MINUTE, 45); 
cal1.set(Calendar.SECOND, 00); 

Calendar cal2 = Calendar.getInstance(); 
cal2.set(Calendar.HOUR_OF_DAY, 17); 
cal2.set(Calendar.MINUTE, 30); 
cal2.set(Calendar.SECOND, 00); 

// Test if the times are in the past, if they are add one day 
Calendar now = Calendar.getInstance(); 
if(now.after(cal1)) 
    cal1.add(Calendar.HOUR_OF_DAY, 24); 
if(now.after(cal2)) 
    cal2.add(Calendar.HOUR_OF_DAY, 24); 

// Create two different PendingIntents, they MUST have different requestCodes 
Intent intent = new Intent(this, AlarmReceiver.class); 
PendingIntent morningAlarm = PendingIntent.getBroadcast(getApplicationContext(), 0, intent, 0); 
PendingIntent eveningAlarm = PendingIntent.getBroadcast(getApplicationContext(), 1, intent, 0); 

// Start both alarms, set to repeat once every day 
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE); 
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, cal1.getTimeInMillis(), DateUtils.DAY_IN_MILLIS, morningAlarm); 
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, cal2.getTimeInMillis(), DateUtils.DAY_IN_MILLIS, eveningAlarm); 
弄明白