Как отменить этот повторяющийся сигнал тревоги? - PullRequest
34 голосов
/ 25 июля 2010

Я пишу что-то вроде напоминания для пользователей.Пользователи будут устанавливать напоминания для своих событий, когда придет время, будет установлен повторяющийся сигнал тревоги для запуска уведомления в строке состояния.Но сигнал тревоги кажется безостановочным после того, как я выбрал уведомление или очистил уведомление.Я не уверен, где отменить этот повторяющийся сигнал.Ниже приведены некоторые из кодов: Установите повторяющуюся тревогу в моей основной деятельности

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);

Как отключить сигнал тревоги, когда пользователь выбирает уведомление или сбрасывает его?

Ответы [ 3 ]

79 голосов
/ 25 июля 2010

Позвоните cancel() на 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);
4 голосов
/ 15 ноября 2016

Я пробовал разные методы и не мог заставить его работать, поэтому я решил сделать подвох.Когда я хочу отменить повторяющуюся тревогу, я использую тот же метод, который создал мою тревогу (и, следовательно, заменил старую), а затем сразу же отменю ее.При использовании этого метода, если для логической переменной задано значение 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 голосов
/ 26 июня 2015

В вашем 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();
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...