Уведомления повторяются при использовании приложения - PullRequest
0 голосов
/ 04 ноября 2019

Я создал уведомления, которые отображаются в определенное время, которое я установил в общих настройках. Уведомления работают правильно в установленное время, однако они также отображаются, когда я использую приложение примерно каждую минуту. Если я удалю их из панели навигации через некоторое время, уведомление будет передано повторно. Как я могу отправлять уведомления только в установленное время? Я нахожусь в Android 8 Api 26

Это класс, который я инициализирую в onCreate MainActivity, чтобы установить Alarm Manager

public class NotificationApp {


    private Context CONTEXT;

    public NotificationApp(Context context) {
        this.CONTEXT = context;

    }

    public void SetNotification() {

        SharedPreferencesApp sharedPreferencesApp = new SharedPreferencesApp(CONTEXT);

        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(System.currentTimeMillis());
        calendar.set(Calendar.HOUR_OF_DAY, sharedPreferencesApp.getHourPreferences());
        calendar.set(Calendar.MINUTE, sharedPreferencesApp.getMinutesPreferences() - 1);
        calendar.set(Calendar.SECOND, 1);


        Intent intentNotificationApp = new Intent(CONTEXT, NotificationApp.Notification_reciver.class);
        intentNotificationApp.setAction("MY_NOTIFICATION_MESSAGE");
        PendingIntent pendingIntent = PendingIntent.getBroadcast(CONTEXT, 0, intentNotificationApp, PendingIntent.FLAG_UPDATE_CURRENT);

        AlarmManager alarmManager = (AlarmManager) CONTEXT.getSystemService(Context.ALARM_SERVICE);
        alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);

    }

В onCreate () MainActivity new NotificationApp(getActivityContext()).SetNotification();

Тогда класс, который расширяет BroadcastReceiver


        public Notification_reciver() {

        }

        @SuppressLint("UnsafeProtectedBroadcastReceiver")
        @Override
        public void onReceive(Context context, Intent intent) {
            if (Objects.equals(intent.getAction(), "MY_NOTIFICATION_MESSAGE")) {
                NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

                Intent intentGetNotificationExpired = new Intent(context, ArticoliScaduti.class);
                intentGetNotificationExpired.putExtra("today", true);
                intentGetNotificationExpired.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

                PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intentGetNotificationExpired, PendingIntent.FLAG_UPDATE_CURRENT);

                NotificationCompat.Builder notificationBuilderExpired = new NotificationCompat.Builder(context, "dispensa_channel")
                        .setSmallIcon(R.drawable.icon)
                        .setContentTitle("title text")
                        .setContentText("body text")
                        .setPriority(NotificationCompat.PRIORITY_DEFAULT)
                        .setContentIntent(pendingIntent)
                        .setAutoCancel(true)
                        .addAction(R.drawable.ic_launcher_background, "some_text", pendingIntent);

                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                    NotificationChannel channel = new NotificationChannel("notificationChannelOne", "channel", NotificationManager.IMPORTANCE_DEFAULT);
                    channel.setDescription("name_channel");

                    ((NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE)).createNotificationChannel(channel);
                    notificationBuilderExpired.setChannelId(channel.getId());
                }

                notificationManager.notify(0, notificationBuilderExpired.build());
            }
        }
    }


}

1 Ответ

0 голосов
/ 07 ноября 2019

Решено! Проблема заключалась в том, что инициализация Сервиса более одного раза решалась путем установки параметра, который устанавливает инициализацию или нет в общих настройках, чтобы она инициализировалась только один раз.

...