android 如果当天的闹钟时间已过,则防止立即触发闹钟服务

android prevent immediate trigger of alarm service if alarm time has passed for the day

警报管理器的参考资料说

If the stated trigger time is in the past, the alarm will be triggered immediately.

我在申请中遇到了这个问题。这是我的警报管理器代码:

Intent myIntent = new Intent(getActivity(), DinnerAlarmReceiver.class);
                pendingDinnerIntent = PendingIntent.getBroadcast(getActivity(), 0, myIntent, 0);

                Calendar calendar = Calendar.getInstance();
                calendar.set(Calendar.HOUR_OF_DAY, hourOfDay);
                calendar.set(Calendar.MINUTE, minute);

                alarmManager.set(AlarmManager.RTC_WAKEUP,
                        calendar.getTimeInMillis(), pendingDinnerIntent);

这个问题有解决办法吗?

-----编辑-----

我写了一些代码来估计闹钟的设置时间是否早于当前时间。这是上面的部分并进行了相应的更改:

Calendar calendar = Calendar.getInstance();
                long currentTime = calendar.getTimeInMillis();
                calendar.set(Calendar.HOUR_OF_DAY, hourOfDay);
                calendar.set(Calendar.MINUTE, minute);
                long setTime = calendar.getTimeInMillis();
                Timestamp setTimestamp = new Timestamp(setTime);
                Timestamp currentTimestamp = new Timestamp(currentTime);
                if (setTimestamp.after(currentTimestamp))
                {
                    alarmManager.set(AlarmManager.RTC_WAKEUP,
                            calendar.getTimeInMillis(), pendingDinnerIntent);
                }
                else
                {
                }

如果 setTimestampcurrentTimestamp 之前,我应该 alarmManager 做什么?

您不需要创建 Timestamp。你可以用你的 Calendar.

Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, hourOfDay);
calendar.set(Calendar.MINUTE, minute);

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

alarmManager.set(AlarmManager.RTC_WAKEUP,
    calendar.getTimeInMillis(), pendingDinnerIntent);

我还要提到,对于 KitKat,如果您的 targetSdkVersion 是 19 或以上,则 AlarmManager#set() 方法不准确。如果您希望闹钟在准确的时间触发,您需要使用 setExact*() 方法。