Last Updated: February 25, 2016
·
12.39K
· alberovalley

Cancel a Service that has been scheduled with AlarmManager

Here I explain how to schedule your service so that the AlarmManager will fire with a given periodicity. Now I'll show how to unshcedule the same service.

If your app allows to change the periodicity of the service, you'll want to cancel the previous alarm to make sure you don't just end up with a pile of independent alarms firing up your service. Here's how.

Context ctx = getApplicationContext();
/** */
AlarmManager am = (AlarmManager) ctx.getSystemService(Context.ALARM_SERVICE);
Intent cancelServiceIntent = new Intent(ctx, NewsCheckingService.class);
PendingIntent cancelServicePendingIntent = PendingIntent.getBroadcast(
    ctx,
    NewsCheckingService.SERVICE_ID, // integer constant used to identify the service
    cancelServiceIntent,
    0 //no FLAG needed for a service cancel
    );
am.cancel(cancelServicePendingIntent);

Using the SERVICE_ID that we have prepared in our NewsCheckingService class, AlarmManager knows which alarm must be cancelled.