Еженедельное уведомление появляется в течение минуты после установки напоминания - PullRequest
0 голосов
/ 10 сентября 2018

Я новичок в Android, и в настоящее время я работаю над уведомлениями.

У меня есть 2 типа уведомлений для отображения. один - еженедельное напоминание, а другой - ежемесячное.

Вот как я установил еженедельное напоминание:

manager.setRepeating(AlarmManager.RTC_WAKEUP, currentTime, AlarmManager.INTERVAL_DAY *7, pendingIntent);

и вот как я установил ежемесячное напоминание:

long monthlyDuration = getDuration();
manager.setRepeating(AlarmManager.RTC_WAKEUP, currentTime, monthlyDuration, pendingIntent);




private long getDuration(){
        // get todays date
        Calendar cal = Calendar.getInstance();
        // get current month
        int currentMonth = cal.get(Calendar.MONTH);

        // move month ahead
        currentMonth++;
        // check if has not exceeded threshold of december

        if(currentMonth > Calendar.DECEMBER){
            // alright, reset month to jan and forward year by 1 e.g fro 2013 to 2014
            currentMonth = Calendar.JANUARY;
            // Move year ahead as well
            cal.set(Calendar.YEAR, cal.get(Calendar.YEAR)+1);
        }

        // reset calendar to next month
        cal.set(Calendar.MONTH, currentMonth);
        // get the maximum possible days in this month
        int maximumDay = cal.getActualMaximum(Calendar.DAY_OF_MONTH);


        cal.set(Calendar.DAY_OF_MONTH, maximumDay);
        long thenTime = cal.getTimeInMillis(); 



        return (thenTime); 

    }

Вот код уведомления:

   int importance = NotificationManager.IMPORTANCE_HIGH;

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

       NotificationManager notificationManager = (NotificationManager) context.getSystemService(context.NOTIFICATION_SERVICE);
        Intent notificationIntent = new Intent(context, MainActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(context, 0,
                notificationIntent, 0);
        NotificationCompat.Builder builder = new NotificationCompat.Builder(context, "default");

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            CharSequence name = context.getString(R.string.channel_name);
            String description = context.getString(R.string.col_week_rem_description);
            NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, importance);
            channel.setDescription(description);
            notificationManager.createNotificationChannel(channel);
        }

        builder.setAutoCancel(false);
        builder.setChannelId(CHANNEL_ID);
        builder.setContentTitle(context.getResources().getString(R.string.app_name));
        builder.setContentText(context.getResources().getString(R.string.notification_text));

        if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {

            builder.setSmallIcon(R.drawable.ic_launcher_notification);

            int myColor =
                    context.getResources().getColor(R.color.notification_icon_bg);

            builder.setColor(myColor);

        }
        else {

            builder.setSmallIcon(R.drawable.ic_launcher);

        }

        builder.setContentIntent(pendingIntent);
//        builder.setOngoing(true);
//        builder.setNumber(100);
        notificationManager.notify(NOTIFICATION_ID,builder.build());


    }

Проблема, с которой я сталкиваюсь, заключается в том, что уведомление выскакивает в течение одной или двух минут с момента, когда установлена ​​опция показа напоминания. Что я хочу сделать, так это то, что когда пользователь выбирает еженедельное напоминание, он / она должен получать уведомление одновременно через 7 дней. т.е. если я выберу еженедельное напоминание сегодня в 3 часа. Затем я должен получить уведомление через 3 часа после 7 дней со дня, когда пользователь выбрал еженедельное напоминание. Ежемесячное напоминание также работает таким же образом.

Я прошел через множество тем здесь и в других местах, но не смог решить проблему. Может кто-нибудь, пожалуйста, помогите мне решить проблему.

Спасибо.

1 Ответ

0 голосов
/ 10 сентября 2018
public static void setReminder(Context ctx) {

        Calendar setcalendar = Calendar.getInstance();
        // setcalendar.set(Calendar.DAY_OF_WEEK, 3);

        setcalendar.set(Calendar.HOUR_OF_DAY, //notification hr);
        setcalendar.set(Calendar.MINUTE, //notification min.);
        setcalendar.set(Calendar.SECOND, //notification sec.);
        setcalendar.set(Calendar.DAY_OF_WEEK, //notification day);



        Intent intent = new Intent(ctx, NotificationReceiver.class);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(ctx, id, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        AlarmManager am = (AlarmManager) ctx.getSystemService(Activity.ALARM_SERVICE);

        long timeMs = setcalendar.getTimeInMillis();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            am.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, timeMs, pendingIntent);
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            am.setExact(AlarmManager.RTC_WAKEUP, timeMs, pendingIntent);
        } else {
            am.set(AlarmManager.RTC_WAKEUP, timeMs, pendingIntent);
        }

        Log.e("", "setReminder: reminder has been set");
    }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...