如何每天使用alarmmanager 2次?

时间:2012-12-14 13:09:27

标签: android alarmmanager

我已经使用以下代码每天只设置一次alarmmanager,我希望有2个不同的时间设置,所以每天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);
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);

2 个答案:

答案 0 :(得分: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);

答案 1 :(得分:-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);
}