正如标题所暗示的,我希望安排一项任务在特定日期的特定时间运行。例如,我可能让它在每周二和周四的 5:00 运行。我见过several scheduling methods for Android ,但它们似乎都是以“n延迟后执行任务”或“每n秒执行任务”的形式操作的。
现在我可能可以通过让它在任务本身执行期间计算下一次执行的时间来临时操纵它,但这看起来不太优雅。有更好的方法吗?
最佳答案
您必须设置闹钟才能执行这些任务。一旦触发警报,您很可能最终会调用服务:
private void setAlarmToCheckUpdates() {
Calendar calendar = Calendar.getInstance();
if (calendar.get(Calendar.HOUR_OF_DAY)<22){
calendar.set(Calendar.HOUR_OF_DAY, 22);
} else {
calendar.add(Calendar.DAY_OF_YEAR, 1);//tomorrow
calendar.set(Calendar.HOUR_OF_DAY, 22); //22.00
}
Intent myIntent = new Intent(this.getApplicationContext(), ReceiverCheckUpdates.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this.getApplicationContext(), 0, myIntent,0);
AlarmManager alarmManager = (AlarmManager)this.getApplicationContext().getSystemService(ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
}
但是,如果您需要具体设置一天:
int weekday = calendar.get(Calendar.DAY_OF_WEEK);
if (weekday!=Calendar.THURSDAY){//if we're not in thursday
//we calculate how many days till thursday
//days = The limit of the week (its saturday) minus the actual day of the week, plus how many days till desired day (5: sunday, mon, tue, wed, thur). Modulus of it.
int days = (Calendar.SATURDAY - weekday + 5) % 7;
calendar.add(Calendar.DAY_OF_YEAR, days);
}
//now we just set hour to 22.00 and done.
上面的代码有点棘手和数学化。如果您不想做一些愚蠢而又简单的事情:
//dayOfWeekToSet is a constant from the Calendar class
//c is the calendar instance
public static void SetToNextDayOfWeek(int dayOfWeekToSet, Calendar c){
int currentDayOfWeek = c.get(Calendar.DAY_OF_WEEK);
//add 1 day to the current day until we get to the day we want
while(currentDayOfWeek != dayOfWeekToSet){
c.add(Calendar.DAY_OF_WEEK, 1);
currentDayOfWeek = c.get(Calendar.DAY_OF_WEEK);
}
}
关于android - 在 Android 中安排一周中的某些天的任务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19427006/