如何取消服务中的警报?

时间:2011-04-17 12:50:52

标签: android android-alarms

我使用服务来更新appwidget,并为定期更新安排了重复警报(即它仍然调用服务类)。我现在的问题是,当从主屏幕删除appwidget时,我不知道如何取消闹钟并停止服务。我已尝试取消appwidget的onDeleted()中的警报,其中包含创建警报的相同待处理意图,但它没有取消它。

以下是服务计划的代码:

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); 

然后在appWidgetProviderClass的onDeleted()中:

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);
}

如果我做错了,你能指出吗?感谢。

只是旁注,留下那些注释码,只是为了让你们知道我也尝试过。

1 个答案:

答案 0 :(得分:1)

您需要使用PendingIntentcancel()相同的setRepeating()setClass()使用的setRepeating()相同。换句话说:

  • 如果您在Intent setClass()上致电cancel(),则需要在setAction()意图
  • 上拨打相同的setRepeating()
  • 如果您在Intent setAction()上致电cancel(),则需要在setData()意图
  • 上拨打相同的setRepeating()
  • 如果您在Intent setData()上致电cancel(),则需要在Uri意图
  • 上拨打相同的{{1}}

额外内容无关紧要,但组件(类),操作,数据({{1}})和MIME类型都很重要。