Introduction to AlarmManager

January 1, 2018 Oclemy Android Alarm 2 minutes, 20 seconds

AlarmManager is a class that allows us create alarms. Alarms allow our apps to schedule specific codes to be executed at certain times in the future.

public class AlarmManager extends Object{}

It's better and more efficient to use AlarmManager class to create alarms for scheduling than using something like a timer.

AlarmManager provides to us the access to system alarm services, so it's not like we are going to invent our scheduling algorithms.

AlarmManager is mostly used together with BroadcastReceivers. Here's how it works:

  • First Alarm goes off or rings.
  • The system broadcasts an intent. This is the intent which had been registered for it.
  • This automatically starts the target application in case it's not already running.
  • If the device sleeps, the alarms that are already registered get retained.
  • If the alarm goes off while the device is sleeping, then the device is woken up. This is optional.
  • If the user turns the device off or reboots it, then the alarms are cleared.

You are guaranteed that the phone will not sleep till you have finished handling your broadcast. Broadcast are handled by the onReceive() method of the android.content.BroadcastReceiver. This is a method you override after deriving this class.

As long as the The onReceive() method is still executing, the AlarmManager will hold a CPU wake lock. So the device won't sleep.

Then the AlarmManager releases the wake lock when the onReceive() finishes executing and returns.

But sometimes just as the onReceive() method finishes, it's possible that the phone can sleep immediately. Because the device has slept quickly, if you had requested a service using the Context.startService() it won't be started. This is because the device has slept before it's called. However, the initial wake lock is no longer in place. It had been released the moment the onReceive() had returned. So what's the solution? Well you implement a separate wake lock on your BroadcastReceiver and Service. This wake lock will ensure the device runs until the service becomes available.

So when should you use alarm manager and when should you not? Well use alarm manager for scheduling operations. Don't use it for timing and ticking operations. And don't use timers for scheduling operations. Scheduled code using alarmmanager do not require teh application to be running all the time. If you used a timer then it would have to run throughout. This wastes memory and processing time.

The Android Operating System shifts alarms so us minimize wakeups and battery use. This is starting from Android API 19(KitKat). This the alarms may not be strictly exact. If you need to be strictly exact, then you can use the setExact() method.

AlarmManager is not directly instantiated. Instead you use the static getSystemService() of the Context class. You pass the Context.ALARM_SERVICE flag.