Как отменить этот повторяющийся сигнал?
Я пишу что-то вроде напоминания для пользователей. Пользователи будут устанавливать напоминания о своих событиях, когда придет время, будет установлен повторный сигнал тревоги, чтобы вызвать уведомление о состоянии. Но тревога кажется бесполезна после того, как я выбрал уведомление или очистил уведомление. Я не знаю, где отменить эту повторяющуюся тревогу. Ниже приведены некоторые из кодов:
Настройка повторяющегося сигнала тревоги в моем основном действии
alarmTime = Calendar.getInstance();
Intent intent = new Intent(this, AlarmReceive.class);
PendingIntent sender = PendingIntent.getBroadcast(this, 0, intent, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmTime.add(Calendar.MINUTE,offset_time);
//Schedule the alarm
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, alarmTime.getTimeInMillis(), 30 * 1000, sender);
В моем методе OnReceive я просто показываю уведомление в строке состояния и устанавливаю флаг как FLAG_AUTO_CANCEL
manager = (NotificationManager) context.getSystemService(context.NOTIFICATION_SERVICE);
// Set the icon, scrolling text and timestamp
Notification notification = new Notification(R.drawable.medical, text, System.currentTimeMillis());
PendingIntent contentIntent = PendingIntent.getActivity(context, 0, i, 0);
notification.flags = Notification.FLAG_AUTO_CANCEL;
manager.notify(R.string.service_text, notification);
Как я могу остановить будильник, когда пользователь выбирает уведомление или очищает его?
Ответы
Ответ 1
Вызовите cancel()
on AlarmManager
с эквивалентом PendingIntent
к тому, который вы использовали с setRepeating()
:
Intent intent = new Intent(this, AlarmReceive.class);
PendingIntent sender = PendingIntent.getBroadcast(this, 0, intent, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.cancel(sender);
Ответ 2
Я пробовал различные методы и не мог заставить его работать, поэтому я решил сделать грязный трюк. Когда я хочу отменить свою повторяющуюся тревогу, я использую тот же метод, который создал мой будильник (и, следовательно, заменил старый), а затем сразу же отменил его. С помощью этого метода, если логическая переменная установлена в true, она создает аварийный сигнал, который она заменяет, а затем отменяет замену, которая имеет тот же идентификатор:
static void CancelRepeatingAlarm(Context context, boolean creating){
//if it already exists, then replace it with this one
Intent alertIntent = new Intent(context, AlertReceiver.class);
PendingIntent timerAlarmIntent = PendingIntent
.getBroadcast(context, 100, alertIntent,PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
if (creating){
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), INTERVAL, timerAlarmIntent);
}else{
alarmManager.cancel(timerAlarmIntent);
}
Ответ 3
В MainActivity
установите время будильника. Если вы собираетесь использовать несколько аварийных сигналов, используйте SharedPreferences
для хранения своих идентификаторов. Вот код:
PendingIntent pendingIntent = PendingIntent.getBroadcast(MainActivity.this, _id,intent, PendingIntent.FLAG_UPDATE_CURRENT);
alarmManager = (AlarmManager) getSystemService(Activity.ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, targetCal.getTimeInMillis(),
pendingIntent);
public static Context getContext() {
return mContext;
}
mContext=mainactivity.this;
В вашем втором Activity
используйте тот же идентификатор от SharedPreferences
. В моем коде я получаю идентификатор из ArrayList, Alarm_id
. Наконец, здесь вы можете использовать контекст MainActivity с MainActivity.getContext()
. Вот код:
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent intentAlarm = new Intent(AlarmListviewActivity.this,
MainActivity.class);
PendingIntent morningIntent = PendingIntent.getBroadcast(MainActivity.getContext(), Alarm_id.get(positon),
intentAlarm, PendingIntent.FLAG_CANCEL_CURRENT);
alarmManager.cancel(morningIntent);
morningIntent.cancel();