2017-06-09 24 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); 
弄明白