Почему менеджер аварийных сигналов с IntentService продолжает отправлять уведомления, когда время истекло - PullRequest
0 голосов
/ 10 ноября 2019

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

Вот мой код

Служба намерений

public class PrayerIntentService extends IntentService {

    public static final String ACTION_SEND_NOTIFICATION_PARAM = "ACTION_SEND_NOTIFICATION";
    public static final String EXTRA_PRAYER_NAME_PARAM = "EXTRA_PRAYER_NAME";
    public static final String EXTRA_PRAYER_TIME_PARAM = "EXTRA_PRAYER_TIME";
    private String prayerName;
    private String prayerTime;

    public PrayerIntentService() {
        super("ScheduledService");
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        Log.d(getClass().getSimpleName(), "I ran!");

        prayerName = intent.getStringExtra(EXTRA_PRAYER_NAME_PARAM);
        prayerTime = intent.getStringExtra(EXTRA_PRAYER_TIME_PARAM);

        setPrayerNotificationListener(this);

    }

    private void setPrayerNotificationListener(Context context) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
            Context applicationContext = Objects.requireNonNull(context).getApplicationContext();
            Intent intent = new Intent(applicationContext, SplashActivity.class);
            PendingIntent contentIntent = PendingIntent.getActivity(applicationContext, 0,
                    intent, PendingIntent.FLAG_UPDATE_CURRENT);

            NotificationCompat.Builder b = new NotificationCompat.Builder(applicationContext);

            b.setAutoCancel(true)
                    .setDefaults(Notification.DEFAULT_ALL)
                    .setWhen(System.currentTimeMillis())
                    .setSmallIcon(R.mipmap.ic_launcher_round)
                    .setTicker(context.getString(R.string.app_name))
                    .setContentTitle(context.getString(R.string.notification_title))
                    .setContentText(prayerName + " :" + prayerTime)
                    .setSound(Uri.parse("android.resource://"
                            + context.getPackageName() + "/" +
                            new SettingsPreferences(context).getPrayerSoundResource()))
                    .setContentIntent(contentIntent);
            // .setContentInfo(context.getString(R.string.next_prayer));


            NotificationManager notificationManager =
                    (NotificationManager) applicationContext.getSystemService(Context.NOTIFICATION_SERVICE);
            notificationManager.notify(1, b.build());
        } else {

            NotificationManager notificationManager = (NotificationManager) Objects.requireNonNull(context).getSystemService(Context.NOTIFICATION_SERVICE);
            String NOTIFICATION_CHANNEL_ID = context.getString(R.string.notif_channel_id);

            NotificationChannel notificationChannel =
                    new NotificationChannel(NOTIFICATION_CHANNEL_ID, context.getString(R.string.salah),
                            NotificationManager.IMPORTANCE_UNSPECIFIED);
            // Configure the notification channel.
            notificationChannel.setDescription("Channel description");
            notificationChannel.enableLights(true);
            notificationChannel.setLightColor(context.getColor(R.color.colorPrimary));
            notificationChannel.setVibrationPattern(new long[]{0, 1000, 500, 1000});
            notificationChannel.enableVibration(true);
            notificationManager.createNotificationChannel(notificationChannel);


            NotificationCompat.Builder notificationBuilder = new NotificationCompat.
                    Builder(context.getApplicationContext(), NOTIFICATION_CHANNEL_ID);

            notificationBuilder.setAutoCancel(true)
                    .setDefaults(Notification.DEFAULT_ALL)
                    .setWhen(System.currentTimeMillis())
                    .setSmallIcon(R.mipmap.ic_launcher_round)
                    .setTicker(context.getString(R.string.app_name))
                    .setContentTitle(context.getString(R.string.notification_title))
                    .setContentText(prayerName + " :" + prayerTime)
                    .setSound(Uri.parse("android.resource://"
                            + context.getPackageName() + "/" +
                            new SettingsPreferences(context).getPrayerSoundResource()));
            // .setContentInfo(context.getString(R.string.next_prayer));
            DateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
            Date date = new Date();
            String now = dateFormat.format(date);
            notificationManager.notify(Integer.valueOf(now.substring(3, 6)), notificationBuilder.build());
        }
    }
}

Диспетчер аварийных сигналов

public class PrayerAlarmManger {

    private PendingIntent pendingIntent = null;

    public void setAlarm(Context context, Long alarmTime, String prayerName, String prayerTime, int requestCode) {
        AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);

        Intent intent = new Intent(context, PrayerIntentService.class);
        intent.setAction(PrayerIntentService.ACTION_SEND_NOTIFICATION_PARAM);
        intent.putExtra(PrayerIntentService.EXTRA_PRAYER_NAME_PARAM, prayerName);
        intent.putExtra(PrayerIntentService.EXTRA_PRAYER_TIME_PARAM, prayerTime);

        pendingIntent = PendingIntent.getService(context, requestCode, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, alarmTime, pendingIntent);
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            alarmManager.setExact(AlarmManager.RTC_WAKEUP, alarmTime, pendingIntent);
        } else {
            alarmManager.set(AlarmManager.RTC_WAKEUP, alarmTime, pendingIntent);
        }
    }

Установка диспетчера аварийных сообщений из onCreate внутри активности

public class PrayersActivity extends BaseActivity{ 

   private AlarmManager managerFajr, managerShrouq, managerZuhr, managerAsr, managerMaghrib, managerEshaa;
   private PendingIntent pendingIntentFajr, pendingIntentShrouq, pendingIntentZuhr, pendingIntentAsr,
            pendingIntentMaghrib, pendingIntentEshaa;

 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        startAlarm();
} 
    public void startAlarm() {
        Time timeFajr, timeShrouq, timeZuhr, timeAsr, timeMaghrib, timeEshaa;
        Intent prayerIntentFajr, prayerIntentShrouq, prayerIntentZuhr, prayerIntentAsr, prayerIntentMaghrib, prayerIntentEshaa;
        Calendar calendarFajr, calendarShrouq, calendarZuhr, calendarAsr, calendarMaghrib, calendarEshaa;
        String[] prayersName = {getString(R.string.fajr), getString(R.string.shrouq), getString(R.string.zohr),
                getString(R.string.asr), getString(R.string.maghrb), getString(R.string.esha)};
                managerFajr = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
                timeFajr = PrayerTimesHelper.getFajrPrayerTime(this, PrayerTimesHelper.getCurrentSimpleDate());

                calendarFajr = Calendar.getInstance();
                calendarFajr.set(Calendar.HOUR_OF_DAY, timeFajr.getHour());
                calendarFajr.set(Calendar.MINUTE, timeFajr.getMinute());

                if (calendarFajr.before(Calendar.getInstance())) {
                    calendarFajr.add(Calendar.DATE, 1);
                }

                if (notificationsPreferences.getFajrNotification()) {

                    new PrayerAlarmManger().setAlarm(this, calendarFajr.getTimeInMillis(), prayersName[0], AppUtils.convertTimeAMandPM("" +
                            PrayerTimesHelper.getFajrPrayerTime(this, PrayerTimesHelper.getCurrentSimpleDate())), 100);
                }

                managerShrouq = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
                timeShrouq = PrayerTimesHelper.getShrouqPrayerTime(this, PrayerTimesHelper.getCurrentSimpleDate());

                calendarShrouq = Calendar.getInstance();
                calendarShrouq.set(Calendar.HOUR_OF_DAY, timeShrouq.getHour());
                calendarShrouq.set(Calendar.MINUTE, timeShrouq.getMinute());

                if (calendarShrouq.before(Calendar.getInstance())) {
                    calendarShrouq.add(Calendar.DATE, 1);
                }

                new PrayerAlarmManger().setAlarm(this, calendarShrouq.getTimeInMillis(), prayersName[1], AppUtils.convertTimeAMandPM("" +
                        PrayerTimesHelper.getShrouqPrayerTime(this, PrayerTimesHelper.getCurrentSimpleDate())), 101);


                managerZuhr = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
                timeZuhr = PrayerTimesHelper.getZuhrPrayerTime(this, PrayerTimesHelper.getCurrentSimpleDate());

                calendarZuhr = Calendar.getInstance();
                calendarZuhr.set(Calendar.HOUR_OF_DAY, timeZuhr.getHour());
                calendarZuhr.set(Calendar.MINUTE, timeZuhr.getMinute());

                if (calendarZuhr.before(Calendar.getInstance())) {
                    calendarZuhr.add(Calendar.DATE, 1);
                }

                new PrayerAlarmManger().setAlarm(this, calendarZuhr.getTimeInMillis(), prayersName[2], AppUtils.convertTimeAMandPM("" +
                        PrayerTimesHelper.getZuhrPrayerTime(this, PrayerTimesHelper.getCurrentSimpleDate())), 102);


                managerAsr = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
                timeAsr = PrayerTimesHelper.getAsrPrayerTime(this, PrayerTimesHelper.getCurrentSimpleDate());

                calendarAsr = Calendar.getInstance();
                calendarAsr.set(Calendar.HOUR_OF_DAY, timeAsr.getHour());
                calendarAsr.set(Calendar.MINUTE, timeAsr.getMinute());

                if (calendarAsr.before(Calendar.getInstance())) {
                    calendarAsr.add(Calendar.DATE, 1);
                }

                new PrayerAlarmManger().setAlarm(this, calendarAsr.getTimeInMillis(), prayersName[3], AppUtils.convertTimeAMandPM("" +
                        PrayerTimesHelper.getAsrPrayerTime(this, PrayerTimesHelper.getCurrentSimpleDate())), 103);

                managerMaghrib = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
                timeMaghrib = PrayerTimesHelper.geMaghribhrouqPrayerTime(this, PrayerTimesHelper.getCurrentSimpleDate());

                calendarMaghrib = Calendar.getInstance();
                calendarMaghrib.set(Calendar.HOUR_OF_DAY, timeMaghrib.getHour());
                calendarMaghrib.set(Calendar.MINUTE, timeMaghrib.getMinute());

                if (calendarMaghrib.before(Calendar.getInstance())) {
                    calendarMaghrib.add(Calendar.DATE, 1);
                }

                new PrayerAlarmManger().setAlarm(this, calendarMaghrib.getTimeInMillis(), prayersName[4], AppUtils.convertTimeAMandPM("" +
                        PrayerTimesHelper.geMaghribhrouqPrayerTime(this, PrayerTimesHelper.getCurrentSimpleDate())), 104);


                managerEshaa = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
                timeEshaa = PrayerTimesHelper.getEshaaPrayerTime(this, PrayerTimesHelper.getCurrentSimpleDate());

                calendarEshaa = Calendar.getInstance();
                calendarEshaa.set(Calendar.HOUR_OF_DAY, timeEshaa.getHour());
                calendarEshaa.set(Calendar.MINUTE, timeEshaa.getMinute());

                if (calendarEshaa.before(Calendar.getInstance())) {
                    calendarEshaa.add(Calendar.DATE, 1);
                }

                new PrayerAlarmManger().setAlarm(this, calendarEshaa.getTimeInMillis(), prayersName[5], AppUtils.convertTimeAMandPM("" +
                        PrayerTimesHelper.getEshaaPrayerTime(this, PrayerTimesHelper.getCurrentSimpleDate())), 105);


    }
}
...