Android: установите все PendingIntents с помощью AlarmManager
Я устанавливаю будильник следующим образом:
alarmManager.set(AlarmManager.RTC_WAKEUP, alarmTime, pendingEvent);
Мне интересно удалить все аварийные сигналы, которые были установлены ранее, и очистить их.
Есть ли способ сделать это или получить все установленные в настоящий момент тревоги, чтобы я мог их вручную удалить?
Ответы
Ответ 1
Вам нужно создать свое ожидающее намерения, а затем отменить его
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent updateServiceIntent = new Intent(context, MyPendingIntentService.class);
PendingIntent pendingUpdateIntent = PendingIntent.getService(context, 0, updateServiceIntent, 0);
// Cancel alarms
try {
alarmManager.cancel(pendingUpdateIntent);
} catch (Exception e) {
Log.e(TAG, "AlarmManager update was not canceled. " + e.toString());
}
Ответ 2
Вам не нужно ссылаться на него. Просто определите новый PendingIntent, как и тот, который вы определили при его создании.
Например:
если я создал PendingIntent, который должен быть запущен AlarmManager следующим образом:
Intent alarmIntent = new Intent(getApplicationContext(), AlarmBroadcastReceiver.class);
alarmIntent.setData(Uri.parse("custom://" + alarm.ID));
alarmIntent.setAction(String.valueOf(alarm.ID));
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
PendingIntent displayIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, alarmIntent, 0);
alarmManager.set(AlarmManager.RTC_WAKEUP, alarmDateTime, displayIntent);
Затем где-то в другом коде (даже в другом действии) вы можете сделать это, чтобы отменить:
Intent alarmIntent = new Intent(getApplicationContext(), AlarmBroadcastReceiver.class);
alarmIntent.setData(Uri.parse("custom://" + alarm.ID));
alarmIntent.setAction(String.valueOf(alarm.ID));
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
PendingIntent displayIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, alarmIntent, 0);
alarmManager.cancel(displayIntent);
Здесь важно установить PendingIntent с точно такими же данными и действием и другими критериями, а также указанными здесь http://developer.android.com/reference/android/app/AlarmManager.html#cancel%28android.app.PendingIntent%29
Ответ 3
Чтобы отменить будильник, вам не нужно воссоздать тот же PendingIntent и передать тот же код запроса.
Итак, я создал AlarmUtits, чтобы помочь мне сохранить все коды запросов в настройках, чтобы отменить его в будущем, если это необходимо. Все, что вам нужно, это использовать следующий класс и вызвать следующие методы:
-
addAlarm
, чтобы добавить новый сигнал и передать код запроса.
-
cancelAlarm
, чтобы удалить будильник, вам необходимо заново создать тот же самый файл
Настройте и передайте тот же код запроса.
-
hasAlarm
, чтобы проверить, добавлен ли этот аварийный сигнал, вам необходимо воссоздать
тот же Intent и передать тот же код запроса.
-
cancelAllAlarms
, чтобы удалить ВСЕ установленные тревоги.
My AlarmUtils
public class AlarmUtils {
private static final String sTagAlarms = ":alarms";
public static void addAlarm(Context context, Intent intent, int notificationId, Calendar calendar) {
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, notificationId, intent, PendingIntent.FLAG_CANCEL_CURRENT);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
alarmManager.setExact(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
} else {
alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
}
saveAlarmId(context, notificationId);
}
public static void cancelAlarm(Context context, Intent intent, int notificationId) {
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, notificationId, intent, PendingIntent.FLAG_CANCEL_CURRENT);
alarmManager.cancel(pendingIntent);
pendingIntent.cancel();
removeAlarmId(context, notificationId);
}
public static void cancelAllAlarms(Context context, Intent intent) {
for (int idAlarm : getAlarmIds(context)) {
cancelAlarm(context, intent, idAlarm);
}
}
public static boolean hasAlarm(Context context, Intent intent, int notificationId) {
return PendingIntent.getBroadcast(context, notificationId, intent, PendingIntent.FLAG_NO_CREATE) != null;
}
private static void saveAlarmId(Context context, int id) {
List<Integer> idsAlarms = getAlarmIds(context);
if (idsAlarms.contains(id)) {
return;
}
idsAlarms.add(id);
saveIdsInPreferences(context, idsAlarms);
}
private static void removeAlarmId(Context context, int id) {
List<Integer> idsAlarms = getAlarmIds(context);
for (int i = 0; i < idsAlarms.size(); i++) {
if (idsAlarms.get(i) == id)
idsAlarms.remove(i);
}
saveIdsInPreferences(context, idsAlarms);
}
private static List<Integer> getAlarmIds(Context context) {
List<Integer> ids = new ArrayList<>();
try {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
JSONArray jsonArray2 = new JSONArray(prefs.getString(context.getPackageName() + sTagAlarms, "[]"));
for (int i = 0; i < jsonArray2.length(); i++) {
ids.add(jsonArray2.getInt(i));
}
} catch (Exception e) {
e.printStackTrace();
}
return ids;
}
private static void saveIdsInPreferences(Context context, List<Integer> lstIds) {
JSONArray jsonArray = new JSONArray();
for (Integer idAlarm : lstIds) {
jsonArray.put(idAlarm);
}
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = prefs.edit();
editor.putString(context.getPackageName() + sTagAlarms, jsonArray.toString());
editor.apply();
}
}