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(…). This solution will probably fail if the user navigates away from all your activities, though. The process will shut down, and your Handler messages will go kaput with it.

So instead of Handler, you will use AlarmManager. AlarmManager is 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 ...

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

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.