I'm trying to have to have 2 repeating alarms triggering same Intent but with different extras:
// first alarm @ 2AM
Calendar calendar1 = Calendar.getInstance();
calendar1.set(Calendar.HOUR_OF_DAY, 2);
calendar1.set(Calendar.MINUTE, 0);
calendar1.set(Calendar.SECOND, 0);
// second alarm @ 3AM
Calendar calendar2 = Calendar.getInstance();
calendar2.set(Calendar.HOUR_OF_DAY, 3);
calendar2.set(Calendar.MINUTE, 0);
calendar2.set(Calendar.SECOND, 0);
// Set both intents with differing extras
Intent intent1 = new Intent(context, Receiver.class);
intent1.putExtra("status", true);
Intent intent2 = new Intent(context, Receiver.class);
intent2.putExtra("status", false);
// Set both pending Intents with differint ids
PendingIntent pendingIntent1 = PendingIntent.getBroadcast(context, 1, intent1, 0);
PendingIntent pendingIntent2 = PendingIntent.getBroadcast(context, 2, intent2, 0);
AlarmManager alarm1 = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarm1.setRepeating(AlarmManager.RTC_WAKEUP, calendar1.getTimeInMillis(),
AlarmManager.INTERVAL_DAY, pendingIntent1);
AlarmManager alarm2 = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarm2.setRepeating(AlarmManager.RTC_WAKEUP, calendar2.getTimeInMillis(),
AlarmManager.INTERVAL_DAY, pendingIntent2);
And here is what is triggered by the Intent
public class Receiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Log.d("MyApp", "Received intent with status : " + intent.getBooleanExtra("status", false));
}
.....
}
But for a strange reason both intents are triggered at approximately 3AM :
Received intent with status : false
Received intent with status : true
What am I doing wrong?
Problem is that AlarmManager.setRepeative
is not accurate as written in the official doc.
I was starting my program at 2:50AM so with the above code, first alarm should have been started 50 minutes beforeso it needs to be triggered but since another alarm is scheduled at 31M, the Android OS decides to wait for the 3AM alarm to trigger both (to lower battery consumption I guess).
Solution is to add 24h to the alarms if needed in order to be sure they are scheduled in the future and not in the past and to use AlarmManager.setExact
which is exact but not repeative. Then Reschedule a new AlarmManager.setExact
every day.
I would suggest to never use AlarmManager.setRepeative
if you need better accuracy than 1 hour.