user712109
user712109

Reputation: 3

How can I cancel an alarm in a service?

I used a service to update an appwidget and also scheduled a repeating alarm for periodic updates (i.e it still calls the service class). my problem now is, I don't know how to cancel the alarm and stop the service when an appwidget is deleted from the home screen. I have tried cancelling the alarm in onDeleted() of the appwidget with the same pending intent that created the alarm, but its not cancelling it.

Here is the code for the service schedule:

Intent widgetUpdate = new Intent();
widgetUpdate.setClass(this, appService.class);  
//widgetUpdate.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE);  
widgetUpdate.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, new int[]{appWidgetId});
//widgetUpdate.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
Uri data = Uri.withAppendedPath(Uri.parse(URI_SCHEME + "://widget/id/"),
  String.valueOf(appWidgetId));
widgetUpdate.setData(data);

PendingIntent newpending = PendingIntent.getService(this, 0, widgetUpdate,
  PendingIntent.FLAG_UPDATE_CURRENT);

AlarmManager alarm = (AlarmManager)getSystemService(ALARM_SERVICE);
alarm.setRepeating(AlarmManager.ELAPSED_REALTIME, 
  SystemClock.elapsedRealtime()+ updateRate, updateRate, newpending); 

then in the onDeleted() of appWidgetProviderClass:

public void onDeleted(Context context, int[] appWidgetIds) {

  for (int appWidgetId : appWidgetIds) { 
    //cancel the alarm
    Intent widgetUpdate = new Intent();
    //widgetUpdate.setClassName(this, appService.class);
    //Uri data = Uri.withAppendedPath(Uri.parse(URI_SCHEME + "://widget/id/"),
    //  String.valueOf(appWidgetId));
    //widgetUpdate.setData(data);
    PendingIntent newpending  = PendingIntent.getService(context, 0, widgetUpdate,
      PendingIntent.FLAG_UPDATE_CURRENT);

    AlarmManager alarm = 
      (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
    alarm.cancel(newpending);
    //cancel the service
    context.stopService(new Intent(context,WeatherService.class);    
  }
  super.onDeleted(context, appWidgetIds);
}

please could you point out if am doing anything wrong? Thanks.

just a side note, have left those commented codes, just to let you guys know i have tried that too.

Upvotes: 0

Views: 1864

Answers (1)

CommonsWare
CommonsWare

Reputation: 1006769

You need to use a PendingIntent with cancel() that is equivalent to the one you used with setRepeating(). In other words:

  • If you call setClass() on the setRepeating() Intent, you need to call the same setClass() on the cancel() Intent
  • If you call setAction() on the setRepeating() Intent, you need to call the same setAction() on the cancel() Intent
  • If you call setData() on the setRepeating() Intent, you need to call the same setData() on the cancel() Intent

Extras do not matter, but the component (class), action, data (Uri), and MIME type all matter.

Upvotes: 1

Related Questions