0

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.

Evgeniy Mishustin
  • 3,343
  • 3
  • 42
  • 81

1 Answers1

1

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.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
  • So it just skipping scheduling the alarm or it is cancelling previous? – Evgeniy Mishustin May 07 '16 at 08:14
  • @LuciusHipan: It should be cancelling the previous alarm, just as if you had called `cancel()`. Since `cancel()` takes a `PendingIntent` as the sole identifier of what alarm to cancel, there can only be one alarm per `PendingIntent`. – CommonsWare May 07 '16 at 10:48
  • So this means, if I have this in OnCreate() scheduled for 10 minutes, but I open application again it 8 minutes, the alarm will not be triggered in 2 minutes from there? – Evgeniy Mishustin May 07 '16 at 13:16
  • @LuciusHipan: I would not expect it to. I have not tried this specific scenario recently and so I forget whether Android does something unexpected here. – CommonsWare May 07 '16 at 13:18
  • I've just tried, and it behaves as I said... It is sad that nowhere in docs appears the issue. I wonder how many developers faced unexact alarm-based events. Thanks for your help. – Evgeniy Mishustin May 07 '16 at 13:38