我使用了一项服务来更新一个应用程序小部件,并为定期更新安排了一个重复警报(即它仍然调用服务类)。我现在的问题是,当从主屏幕删除应用程序小部件时,我不知道如何取消警报并停止服务。我已经尝试在应用程序小部件的 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);
}
请你指出我做错了什么吗?谢谢。
只是一个旁注,留下了那些注释代码,只是为了让你们知道我也试过了。