2

正如标题所暗示的那样,我希望将任务安排在特定日期特定时间运行。例如,我可能让它在每周二和周四的 5:00 运行。我见过几种Android的调度方法,但似乎都是以“延迟n后执行任务”或“每n秒执行任务”的形式运行的。

现在我可能可以通过让它在任务本身执行期间计算下一次执行的时间来陪审它,但这似乎不优雅。有没有更好的方法来做到这一点?

4

1 回答 1

3

您必须设置警报来执行这些任务。一旦触发警报,您​​很可能最终会调用服务:

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);
    }
}
于 2013-10-17T12:46:07.463 回答