サービスを使用してアプリウィジェットを更新し、定期的な更新の繰り返しアラームをスケジュールしました(つまり、サービスクラスを呼び出します)。私の問題は、アプリウィジェットがホーム画面から削除されたときにアラームをキャンセルしてサービスを停止する方法がわからないことです。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);
}
何か悪いことをしているのか指摘していただけますか?ありがとう。
補足として、コメントされたコードを残しました。これは、私も試したことを皆さんに知らせるためです。