Last Updated: August 22, 2016
· alberovalley

Schedule a service using AlarmManager

You have coded a Service - let's call it NewsCheckingService - that handles some operations like http requests to, say, check for news on a given website. Now you want your service to run with a given periodicity (say every 5 minutes) no matter if the app is running or the screen is off. The easiest way is to register an alarm with the AlarmManager to fire up the service:

This code will trigger the service for the first time inmediately. If you want to decide it to start later, use something like this to change the value of the Calendar instance.

Context ctx = getApplicationContext();
/** this gives us the time for the first trigger.  */ 
Calendar cal = Calendar.getInstance(); 
AlarmManager am = (AlarmManager) ctx.getSystemService(Context.ALARM_SERVICE);
long interval = 1000 * 60 * 5; // 5 minutes in milliseconds
Intent serviceIntent = new Intent(ctx, NewsCheckingService.class);
// make sure you **don't** use *PendingIntent.getBroadcast*, it wouldn't work 
PendingIntent servicePendingIntent = 
         NewsCheckingService.SERVICE_ID, // integer constant used to identify the service
         PendingIntent.FLAG_CANCEL_CURRENT);  // FLAG to avoid creating a second service if there's already one running 
// there are other options like setInexactRepeating, check the docs  
    AlarmManager.RTC_WAKEUP,//type of alarm. This one will wake up the device when it goes off, but there are others, check the docs

With that, the Service will fire up first at the time specified by the Calendar instance. After that, every interval milliseconds the Service will fire up again until the device reboots or the alarm is cancelled.

1 Response
Add your response

Thank you soo much!!!, it's hard to find such simplicity at explaining these kind of things.

over 1 year ago ·