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 に答える