首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在Android中将任务安排在一周中的特定日期

在Android中将任务安排在一周中的特定日期
EN

Stack Overflow用户
提问于 2013-10-17 20:39:59
回答 1查看 1.9K关注 0票数 2

正如标题所暗示的,我希望安排一个任务在特定的日期和特定的时间运行。例如,我可以让它在每周二和周四的5:00运行。我见过several scheduling methods for Android,但它们似乎都是以“n延迟后执行任务”或“每n秒执行一次任务”的形式运行的。

现在,我可以通过让它在任务本身的执行过程中计算到下一次执行的时间来随意操纵它,但这似乎并不优雅。有没有更好的方法来做到这一点?

EN

回答 1

Stack Overflow用户

发布于 2013-10-17 20:46:07

你必须设置一个闹钟来执行这些任务。最有可能的是,一旦警报被触发,你将最终调用一个服务:

代码语言:javascript
复制
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);
    }

但是,如果您需要专门设置某一天:

代码语言:javascript
复制
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.

上面的代码有点棘手,而且是数学问题。如果你不想做一些既简单又愚蠢的事情:

代码语言:javascript
复制
//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);
    }
}
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/19427006

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档