2013-10-17 65 views
2

正如標題所暗示的,我正在計劃某個任務在某些特定時間運行。例如,我可能會在每週二和週四的5點運行。我見過several scheduling methods for Android,但他們似乎都以「延遲後做任務」或「每n秒做一次任務」的形式進行操作。在Android中安排一週的某幾天的任務

現在,我可以通過讓它在執行任務本身時計算下一次執行的時間來評估它,但這看起來不夠優雅。有沒有更好的方法來做到這一點?

+0

你讀過:http://developer.android.com/training/scheduling/alarms.html –

+0

使用報警經理將解決您的問題。 –

+0

@MorrisonChang我做到了,但它並不完全符合我的願望。看起來我可能最終會使用AlarmManager來爲每一天安排一項任務,並讓它每週重複一次。或者可能像我在原始問題中提到的一樣。 –

回答

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. 

上面的代碼是有點棘手和數學。如果你wan't一些愚蠢的藏漢一樣簡單:

//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); 
    } 
}