如何延迟 android 重复通知开始

How to delay android repeating notification start

我正在使用此代码启动每 3 天重复一次的通知:

 public void setNotification() {
        boolean alarmUp = (PendingIntent.getBroadcast(this, 10000,
                new Intent(this, NotificationReceiver.class),
                PendingIntent.FLAG_NO_CREATE) != null);

        if (!alarmUp) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTimeInMillis(System.currentTimeMillis());

            calendar.set(Calendar.HOUR_OF_DAY, 12);
            calendar.set(Calendar.MINUTE, 21);

            Intent myIntent = new Intent(this, NotificationReceiver.class);
            int ALARM1_ID = 10000;
            PendingIntent pendingIntent = PendingIntent.getBroadcast(
                    this, ALARM1_ID, myIntent, 0);
            AlarmManager alarmManager = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
            assert alarmManager != null;
            alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis() + AlarmManager.INTERVAL_DAY, AlarmManager.INTERVAL_DAY * 3, pendingIntent);
        }
    }

一切看起来都不错,但我希望我的通知在首次启动应用程序并调用此函数后 1 天开始。我认为 calendar.getTimeInMillis() + AlarmManager.INTERVAL_DAY 参与:

alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis() + AlarmManager.INTERVAL_DAY, AlarmManager.INTERVAL_DAY * 3, pendingIntent);

负责第一次启动。但它看起来不是。即使我将它设置为在 1 天后启动,通知也会在调用此函数后立即显示给用户。 帮忙?

使用 setInexactRepeating() 而不是 setRepeating()。当您使用 setInexactRepeating() 时,Android 会同步来自多个应用程序的重复警报并同时触发它们。

alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, SystemClock.elapsedRealtime() + AlarmManager.INTERVAL_DAY,
    AlarmManager.INTERVAL_DAY * 3, pendingIntent);

注意:

ELAPSED_REALTIME:根据设备启动后的时间触发挂起的 Intent,但不会唤醒设备。经过的时间包括设备处于休眠状态的任何时间。

RTC_WAKEUP: 唤醒设备在指定的时间触发挂起的意图。