我试图在每个星期二上午11点调用一个调度程序,但不知何故下面的代码不起作用。
使用日历对象,我可以获得下一个日程安排&然后在调度程序中进行设置。
有人能指出下面代码中存在哪些错误?
private static final int PERIOD = 7 * 24 * 60 * 60 * 1000;
DateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss", Locale.ENGLISH);
Calendar c = nextDayOfWeek(Calendar.TUESDAY); // Set the day of week at which you want to trigger weekly task
c.set(Calendar.HOUR_OF_DAY, 11); // Set the time at which you want to trigger weekly task
c.set(Calendar.MINUTE, 0);
c.set(Calendar.SECOND,0);
c.set(Calendar.MILLISECOND,0);
boolean weeklyAlarmUp = (PendingIntent.getBroadcast(ctxt, 0, new Intent(ctxt, ScheduledWeeklyService.class), PendingIntent.FLAG_NO_CREATE) != null);
if (!weeklyAlarmUp) {
Intent i = new Intent(ctxt, ScheduledWeeklyService.class);
PendingIntent piWeekly = PendingIntent.getBroadcast(ctxt, 0, i, 0);
AlarmManager alarmMgrWeekly = (AlarmManager)ctxt.getSystemService(Context.ALARM_SERVICE);
alarmMgrWeekly.setRepeating(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(), PERIOD, piWeekly);
}
我的实用程序方法如下所示:
public static Calendar nextDayOfWeek(int dow) {
Calendar date = Calendar.getInstance();
int diff = dow - date.get(Calendar.DAY_OF_WEEK);
if (!(diff > 0)) {
diff += 7;
}
date.add(Calendar.DAY_OF_MONTH, diff);
return date;
}