Search code examples
javaandroidalarmmanager

How to create multiple alarms that fire at the same time but queue execution?


I have two alarms that fire two separate services--one is executed every half-hour, and the other every midnight. At exactly 00:00 of any day, both services will be executed and will need to share a common file. Is there a way for me to execute the two services one after the other (preferably the half-hour one first then the midnight-basis one) when both alarms are fired?

I've tried making the file accessor methods synchronized (that way the services will have to wait for the other to finish) but that doesn't give me any control on which of the services gets executed first.


Solution

  • 2 simple options are:

    1. Have only 1 alarm, every 1/2 hour. Each time it fires, check if you are at Midnight. If you are at Midnight, then run both services.
    2. You can have your alarms run in a single IntentService, or @commonsware's WakefulIntentService. These classes are designed to automatically queue, and not to run simultaneously. That way, when the one service is complete, the other will start automatically i.e. the synchronization is automatic.

    Personally, I would use the 1st option (and I have seen it recommended by @commonsware, so I think its probably the best route).

    It is simple to do, doesn't rely on too many extra classes, and you have full control over which service gets run at which times. You also only need to have a single alarm, rather than 2, which I think will be easier to maintain, and slightly better on power consumption.