android - 在 Android 中安排一周中的某些天的任务

标签 android

正如标题所暗示的,我希望安排一项任务在特定日期的特定时间运行。例如,我可能让它在每周二和周四的 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/

相关文章:

android - 带有滑动操作栏的抽屉布局,如 facebook

android - 两个依赖使用相同的库但版本不同

android套接字文件传输

Android - 在 EditText 中处理 "Enter"

android - Firebase set value 重写 children- Android

Android Studio :failed to resolve:com. 泄漏.slideswitch :app:1. 0.0

android - 如何从Android应用程序中的任何网址流式传输视频?

android - 在 MVVM 架构中用 RxJava 替换 LiveData

android - Flutter 应用程序中 firebase 数据库上的 ValueEventListener

android - 更改 NavigationView 的标题标题