【问题标题】:How can I cancel an alarm in a service?如何取消服务中的警报?
【发布时间】:2012-01-11 22:22:20
【问题描述】:

我使用服务来更新应用程序小部件,并为定期更新安排了重复警报(即它仍然调用服务类)。我现在的问题是,当从主屏幕删除应用程序小部件时,我不知道如何取消警报并停止服务。我已经尝试在应用程序小部件的 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);
}

请你指出我做错了什么?谢谢。

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

【问题讨论】:

    标签: android android-alarms


    【解决方案1】:

    您需要将PendingIntentcancel() 一起使用,这与您与setRepeating() 使用的相同。换句话说:

    • 如果您在setRepeating() Intent 上调用setClass(),则需要在cancel() Intent 上调用相同的setClass()
    • 如果您在setRepeating() Intent 上调用setAction(),您需要在cancel() Intent 上调用相同的setAction()
    • 如果您在setRepeating() Intent 上调用setData(),您需要在cancel() Intent 上调用相同的setData()

    附加内容无关紧要,但组件(类)、操作、数据 (Uri) 和 MIME 类型都很重要。

    【讨论】:

    • 天哪,谢谢,我现在可以享受我的星期天了,我想知道我做错了什么。顺便问一下,如果我可以问,您认为在服务类中安排重复警报是一个好的设计或想法吗?我尝试在配置类中执行此操作,但从未发生过。不知道是不是因为配置类调用了这个服务类。
    • @user712109:抱歉,我无法在摘要中回答这个问题。我不知道“配置类”是什么等等。
    • 哦,对不起,我的意思是用户从配置类中设置更新率,这就是警报如何获取计划值的方式;来自首选项,因为配置类必须首先更新小部件,它是从服务类中完成的。但由于它不是问题的一部分,因此不会打扰您。再次感谢
    • 无论如何,我想说的是,只要从服务中完成所有工作没有任何问题,那就没问题了。谢谢! :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多