@Ser_blyat

AlarmReceiver как отменить оповещение?

Из базы данных берутся даты и имена задач, по времени устанавливаются оповещения. Но если задачу удалить или изменить статус и т.п., т.е. в ситуациях, когда должно отмениться оповещение, оно все равно срабатывает.
Знаю про метод cancel(), но не пойму куда его пихнуть) Помогите плез...
public void remind() {
        /* pendingIntent.cancel();
            alarmManager.cancel(pendingIntent);*/

        Calendar cal = Calendar.getInstance();
        Cursor cursorRemind = database.query(DBHelper.TABLE_TASKS, new String[]{DBHelper.KEY_ID, DBHelper.NAME,
                        DBHelper.TIME_REMIND_LONG, DBHelper.IMAGE}, DBHelper.STATUS + "=?" + " and " + DBHelper.TIME_REMIND_LONG
                        + "!=?" + " and " + DBHelper.TIME_REMIND_LONG + ">?",
                new String[]{String.valueOf(RepresTask.statusOn), String.valueOf(""), String.valueOf(cal.getTimeInMillis())},
                null, null, DBHelper.TIME_REMIND_LONG);


        Calendar time = Calendar.getInstance();
        if (cursorRemind.getCount() > 0) {
            while (cursorRemind.moveToNext()) {
                Intent intent = new Intent(getContext(), AlarmReceiver.class);
                intent.putExtra("name", cursorRemind.getString(1));
                intent.putExtra("image", cursorRemind.getInt(3));

                intent.setData(Uri.parse("timer:" + cursorRemind.getInt(0)));

                PendingIntent pendingIntent = PendingIntent.getBroadcast(getContext(), 0, intent,
                        PendingIntent.FLAG_CANCEL_CURRENT);
                //Intent.FLAG_GRANT_READ_URI_PERMISSION
                time.setTimeInMillis(cursorRemind.getLong(2));

                AlarmManager alarmManager = (AlarmManager) getActivity().getSystemService(ALARM_SERVICE);
                alarmManager.cancel(pendingIntent);//
                alarmManager.set(AlarmManager.RTC_WAKEUP, time.getTimeInMillis(), pendingIntent);

                /*Toast mToast = Toast.makeText(
                        getContext(), "Reminders added to the calendar successfully for "
                                + android.text.format.DateFormat.format(
                                "MM/dd/yy h:mm:aa",
                                time.getTimeInMillis()),
                        Toast.LENGTH_LONG);
                mToast.show();*/
            }
        }

        cursorRemind.close();
    }


Вот мой BroadcastReceiver

public class AlarmReceiver extends BroadcastReceiver {


    @Override
    public void onReceive(Context context, Intent intent) {

        Resources res = context.getResources();
        String name = intent.getStringExtra("name");
        int icon = intent.getIntExtra("image",0);
        Intent notificationIntent = new Intent(context, MainActivity.class);

        notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        PendingIntent contentIntent = PendingIntent.getActivity(context, 0,
                notificationIntent, 0);

        Notification.Builder builder = new Notification.Builder(context);

        builder.setContentIntent(contentIntent)
                .setSmallIcon(icon)
                .setContentTitle("TimeManager")
                .setContentText(name)
                .setLargeIcon(BitmapFactory.decodeResource(res, icon))
                .setDefaults(Notification.DEFAULT_ALL);

        Notification notification = builder.build();
        notification.flags |= Notification.FLAG_AUTO_CANCEL;//Отмена после нажатия на увед

        NotificationManager notificationManager = (NotificationManager) context
                .getSystemService(Context.NOTIFICATION_SERVICE);

        notificationManager.notify(Integer.parseInt(intent.getData().getSchemeSpecificPart()), notification);
    }
}
  • Вопрос задан
  • 138 просмотров
Решения вопроса 1
@red-barbarian
Вот пример Overflow
в доке написано, cancel удаляет все алармы которые подпадают под фильтр filterEquals(Intent).
В описании filterEquals(Intent)
Determine if two intents are the same for the purposes of intent resolution (filtering). That is, if their action, data, type, class, and categories are the same. This does not compare any extra data included in the intents.


т.е. для отмены нужно создать intent такой же как для установки. запихнуть его в pendingintent и запустить cancel
Ответ написан
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы