Alarm Manager的参考说明了这一点
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(),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,minute); long setTime = calendar.getTimeInMillis(); Timestamp setTimestamp = new Timestamp(setTime); Timestamp currentTimestamp = new Timestamp(currentTime); if (setTimestamp.after(currentTimestamp)) { alarmManager.set(AlarmManager.RTC_WAKEUP,pendingDinnerIntent); } else { }
如果setTimestamp在currentTimestamp之前,我应该怎么做alarmManager?
解决方法
您不需要创建时间戳.您可以使用日历执行此操作.
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,pendingDinnerIntent);
我还要提到的是,从KitKat开始,如果你的targetSdkVersion是19或更高,则AlarmManager #set()方法并不准确.如果您希望在准确的时间触发警报,则需要使用setExact *()方法.