AlarmManager schedule Alarm on application start

357 Views Asked by At

this is a very dumb question and I still cannot figure out how does AlarmManager work in Android. Suppose I want to schedule a repeating task every half an hour. I want to schedule it at activity onCreate(). I do something like this:

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my);
        alarmMgr = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
        Intent intent = new Intent(context, AlarmReceiver.class);
        alarmIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
        alarmMgr.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
        AlarmManager.INTERVAL_HALF_HOUR,
        AlarmManager.INTERVAL_HALF_HOUR, alarmIntent);
}

Now my question is how does OS knows that this alarm has already been scheduled? I mean it is not scheduling a new one every time activity creates, is it? Otherwise, after 10 activity launches I would get alarm every three minutes and not half an hour. Please, any Android guru, explanation about the issue.

1

There are 1 best solutions below

5
On BEST ANSWER

Now my question is how does OS knows that this alarm has already been scheduled?

AFAIK, it looks for an existing alarm for an equivalent PendingIntent. Here, by "equivalent PendingIntent", I mean:

  • the same operation (e.g., getBroadcast())
  • the same ID (second parameter to getBroadcast())
  • an equivalent Intent

Here, by "equivalent Intent", I mean that they match on all the routing information, which in your case is the ComponentName generated from this and AlarmReceiver.class. Extras, in particular, do not count for equivalence here.