0

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

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

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

4

1 回答 1

1

您需要使用与您使用的PendingIntentwithcancel()等效的 with setRepeating()。换句话说:

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

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

于 2011-04-17T12:55:48.800 回答