在 Android 中为一周中的某些日子安排任务



正如标题所暗示的那样,我希望安排一个任务在特定日期的特定时间运行。例如,我可能会让它在每个星期二和星期四的 5:00 运行。我见过几种 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);
    }
}

最新更新