我在Android中有一个AlarmManager应用程序,它正常工作除了一件事,如果今天是星期四而我将它设置为星期三,在我完成配置后,它会立即启动,只有当我尝试将其设置为前一天比今天,这是我的代码:
public void setupAlarm(View v){
Calendar cal = Calendar.getInstance();
AlarmManager alarmMgr = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
//Setting up for Monday, as an example
cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
cal.set(Calendar.HOUR_OF_DAY, tPicker.getCurrentHour()); //tPicker is a TimePicker
cal.set(Calendar.MINUTE, tPicker.getCurrentMinute());
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
alarmMgr.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), pIntent(this, Calendar.MONDAY));
}
public static pIntent testThis(Context context, int dayId){
Intent intent = new Intent();
intent.setAction("myIntent.intent.action.CLOCK");
return PendingIntent.getBroadcast(context, dayId, intent, PendingIntent.FLAG_UPDATE_CURRENT);
}
正如我所说,它适用于今天和之后的日子,但为什么如果我前一天设置它会立即开始?我将非常感谢您的帮助,谢谢!
编辑:好的,这就是我根据建议得出的结果,似乎工作正常:我有一个每周的每一天的复选框,例如星期一:
Calendar cal = Calendar.getInstance();
Calendar calMon = Calendar.getInstance();
calMon.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
calMon.set(Calendar.HOUR_OF_DAY, tPicker.getCurrentHour());
calMon.set(Calendar.MINUTE, tPicker.getCurrentMinute());
calMon.set(Calendar.SECOND, 0);
calMon.set(Calendar.MILLISECOND, 0);
if((cal.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) ||
(cal.get(Calendar.DAY_OF_WEEK) > Calendar.MONDAY) ||
((cal.get(Calendar.DAY_OF_WEEK) == Calendar.MONDAY) && (calMon.getTimeInMillis() < System.currentTimeMillis()))){
calMon.add(Calendar.WEEK_OF_MONTH, 1);
}
基本上,如果星期日是星期日,请在日历实例中添加一周,如果日期大于星期一,则执行相同操作,如果当前日期与您设置闹钟的日期相同,但是警报设置的时间低于当前时间,添加一周。
它工作正常,只是提到,对于星期日,添加(WEEK_OF_MONTH,1)它是必须的,因为根据日历实例,星期日总是提前一周。感谢您的帮助,感谢它!
答案 0 :(得分:2)
因为时间已经过去了,它必须通知你,即使是最近 当您将警报设置为在同一天的前一次触发时,也会发生这种情况。
答案 1 :(得分:0)
我面临同样的问题,这是我使用的解决方案。如果你有更好的解决方案,请告诉我。
Calendar now = Calendar.getInstance();
Calendar calSet = Calendar.getInstance();
calSet.set(Calendar.DAY_OF_WEEK, day);
calSet.set(Calendar.HOUR_OF_DAY, hour);
calSet.set(Calendar.MINUTE, min);
if (now.after(calSet)) {
calSet.add(Calendar.DAY_OF_MONTH, 7);
Log.i("location1234", "Set for Next week");
}
alarmManager.set(AlarmManager.RTC_WAKEUP,
calSet.getTimeInMillis(), pendingIntent);