Как установить повторяющийся сигнал тревоги с помощью setExact и как его отменить?


Я устанавливаю уведомления с помощью диспетчера сигналов тревоги и широковещательного приемника. Я попытался использовать метод setInexactRepeating менеджера тревоги, но он не вызывает тревоги в точное время выше API 19.

Поэтому я получил предложение использовать метод setExact и устанавливать сигналы тревоги вручную. Я не знаю, как мне это сделать. Нужно ли мне вычислять даты для каждой недели в течение года?

Также сигналы тревоги, которые я создаю, я хочу удалить то же самое, если событие будет удалено. Как я могу это отменить? С помощью метод отмены я пытался отменить сигнал тревоги. Для проверки я попытался установить несколько сигналов тревоги и удалить его.

Если я удаляю одно событие, то уважаемый сигнал тревоги этого события должен получить отмену, но, возможно, все сигналы тревоги получают отмену, так как я не получаю никакого уведомления после удаления события.

Для этого я использовал уникальный идентификатор. Как окончательный статический int RQS_1 = 1; для установки сигнализации.

Может ли кто-нибудь помочь мне с этим, пожалуйста?

Установка аварийных сигналов:

 public void setNotificationTime(Calendar c)
{

    Date dateFrom = new Date();
    df = new SimpleDateFormat("E MMM dd hh:mm:ss zzzz yyyy");
    try {
        dateFrom = df.parse(startTime);
    }
    catch (ParseException ex) {

    }

    dateFrom.getTime();
    c.setTime(dateFrom);

    hour = c.get(Calendar.HOUR_OF_DAY);
    minute = c.get(Calendar.MINUTE);


    if(notificationTime.equals("10 Minutes Before"))
    {


        c.set(Calendar.HOUR_OF_DAY, hour);
        c.set(Calendar.MINUTE, minute - 10);
        c.set(Calendar.SECOND, 0);
        c.set(Calendar.MILLISECOND, 0);
        c.set(Calendar.DATE, day);
        // c.set(Calendar.DAY_OF_WEEK,);

        SetDay(c);

        notification = c.getTime();
        notificationTime = df.format(notification);

        Toast.makeText(getApplicationContext(),notificationTime,Toast.LENGTH_SHORT).show();

        intent = new Intent(getBaseContext(),NotificationReceiver.class);
        pendingIntent = PendingIntent.getBroadcast(getBaseContext(),RQS_1, intent, 0);
        alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
        alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(), AlarmManager.INTERVAL_DAY * 7, pendingIntent);

    }



    else if(notificationTime.equals("30 Minutes Before"))
    {

        c.set(Calendar.HOUR_OF_DAY, hour);
        c.set(Calendar.MINUTE, minute - 30);
        c.set(Calendar.SECOND, 0);
        c.set(Calendar.MILLISECOND, 0);
        c.set(Calendar.DATE, day);
        // c.set(Calendar.DAY_OF_WEEK,);

        SetDay(c);

        notification = c.getTime();
        notificationTime = df.format(notification);

        Toast.makeText(getApplicationContext(),notificationTime,Toast.LENGTH_SHORT).show();

        intent = new Intent(getBaseContext(),NotificationReceiver.class);
        pendingIntent = PendingIntent.getBroadcast(getBaseContext(),RQS_1, intent, 0);
        alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
        alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(), AlarmManager.INTERVAL_DAY * 7, pendingIntent);

    }
}

Метод SetDay I создали, чтобы установить день, который был выбран пользователем из диалогового окна и установить день.

Функция SetDay:

public void SetDay(Calendar c)
{
    switch (dayOfWeek)
        {
            case  "Mon":
                c.set(Calendar.DAY_OF_WEEK, 2);
                c.getTime();
                Toast.makeText(getApplicationContext(),dayOfWeek,Toast.LENGTH_SHORT).show();
                break;
            case "Tue":
                c.set(Calendar.DAY_OF_WEEK, 3);
                c.getTime();
                Toast.makeText(getApplicationContext(),dayOfWeek,Toast.LENGTH_SHORT).show();
                break;

}

Приемник Уведомлений

 public class NotificationReceiver  extends BroadcastReceiver {


    public static int MY_NOTIFICATION_ID = 0;
    NotificationManager notificationManager;
    Notification myNotification;

    EventTableHelper db;

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


        Toast.makeText(context, "Time is set", Toast.LENGTH_LONG).show();

        db = new EventTableHelper(context);

        List<EventData> testSavings = db.getAllEvents();

        for (EventData ts : testSavings) {
            String log = "from date:" + ts.getFromDate()
                    + " ,to date: " + ts.getToDate()
                    + " ,location: " + ts.getLocation()
                    + " ,title " + ts.getTitle();

            Calendar c = Calendar.getInstance();
            Date date = new Date();
            Date date1 = new Date();
            Log.d("Result: ", log);

            SimpleDateFormat df = new SimpleDateFormat("E MMM dd hh:mm:ss zzzz yyyy");
            SimpleDateFormat df2 = new SimpleDateFormat("hh:mm a");

            try {
                date = df.parse(ts.getFromDate());
                date1 = df.parse(ts.getToDate());
            } catch (ParseException ex) {

            }
            String timeFrom = df2.format(date);
         //   String startTime = String.valueOf(timeFrom);

            String timeTo = df2.format(date1);
           // String endTime = String.valueOf(timeTo);


            String location = ts.getLocation();
            String title = ts.getTitle();


            Intent myIntent = new Intent(context, MainActivity.class);
            PendingIntent pendingIntent = PendingIntent.getActivity(
                    context,
                    0,
                    myIntent,
                    PendingIntent.FLAG_UPDATE_CURRENT);

            if(location.equals(""))
            {
                String msg = "From : " + timeFrom + "nTo : " + timeTo;

                myNotification = new NotificationCompat.Builder(context)
                        .setContentTitle("Event : " + title)
                        .setContentText(msg)
                        .setWhen(System.currentTimeMillis())
                        .setContentIntent(pendingIntent)
                        .setAutoCancel(true)
                        .setSmallIcon(R.drawable.eventicon)
                        .setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
                        .setStyle(new NotificationCompat.BigTextStyle().bigText(msg))
                        .setDefaults(Notification.DEFAULT_SOUND)
                        .build();

            }

            else
            {
                String msg = "From : " + timeFrom + "nTo : " + timeTo + "nAt : " + location;
                myNotification = new NotificationCompat.Builder(context)
                        .setContentTitle("Event : " + title)
                        .setContentText(msg)
                        .setWhen(System.currentTimeMillis())
                        .setContentIntent(pendingIntent)
                        .setAutoCancel(true)
                        .setSmallIcon(R.drawable.eventicon)
                        .setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
                        .setStyle(new NotificationCompat.BigTextStyle().bigText(msg))
                        .setDefaults(Notification.DEFAULT_SOUND)
                        .build();

            }

            Log.i("Notify", "Notification");
            notificationManager =
                    (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
            notificationManager.notify(MY_NOTIFICATION_ID, myNotification);

            myNotification.flags=Notification.FLAG_AUTO_CANCEL;

        }
    }
}

Да забыл добавить код отмены:

 alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
                                intent = new Intent(getApplicationContext(), NotificationReceiver.class);
                                pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), RQS_1, intent, 0);
                                alarmManager.cancel(pendingIntent);

Спасибо..

1 2

1 ответ:

Вот так,

pendingIntent = PendingIntent.getBroadcast(getBaseContext(),RQS_1, intent, 0);
    alarmManager.cancel(pendingIntent); //Remove any alarms with a matching Intent

Для получения дополнительной информации AlarmManager