How to schedule an alarm
Android provides AlarmManager
to create and schedule alarms. Alarms offer the following features:
- Schedule alarms for a set time or interval
- Maintained by the OS, not your application, so alarms are triggered even if your application is not running, or the device is asleep
- Can be used to trigger periodic tasks (such as an hourly news update), even if your application is not running
- Your app does not use resources (such as timers or background services), since the OS manages the scheduling
Alarms are not the best solution if you need a simple delay while your application is running, for example, a short delay for a UI event. For short delays, it's easier and more efficient to use a Handler, as we've done in several previous recipes.
When using alarms, keep these best practices in mind:
- Use as infrequent alarm timing as possible
- Avoid waking up the device
- Use as imprecise timing as possible—the more precise the timing, the more resources required
- Avoid setting...