Delayed Execution with AlarmManager

To actually use your service in the background, you will need some way to make things happen when none of your activities are running. Say, by making a timer that goes off every five minutes or so.

You could do this with a Handler by calling Handler.sendMessageDelayed(…) or Handler.postDelayed(…). But this solution will probably fail if the user navigates away from all your activities. The process will shut down, and your Handler messages will go kaput with it.

So instead of Handler, you will use AlarmManager, a system service that can send Intents for you.

How do you tell AlarmManager what intents to send? You use a PendingIntent. You can use PendingIntent to package up a wish: I want to ...

Get Android Programming: The Big Nerd Ranch Guide, Third Edition now with the O’Reilly learning platform.

O’Reilly members experience live online training, plus books, videos, and digital content from nearly 200 publishers.