2016-11-19 120 views
0

我想每天早上6:00在上午每天運行一次工作服務並做一些工作。因爲我只能設置setPeriod我無法找到在每天早上6點執行或重新安排任務的方法。提前致謝。時間表每天早上6點安排PeriodicTask Android

private static long periodSecs = 7200L; //TODO: Set 6AM everyday 
    private static final String JOB_TAG = "NOTIFICATION_JOB"; 

    private void scheduleJob() { 
     Timber.i("scheduleJob"); 
     Task task = new PeriodicTask.Builder() 
       .setService(Job.class) 
       .setPeriod(periodSecs) 
       .setTag(JOB_TAG) 
       .setRequiredNetwork(Task.NETWORK_STATE_CONNECTED) 
       .setPersisted(true) 
       .setUpdateCurrent(true) 
       .build(); 

     GcmNetworkManager.getInstance(this).schedule(task); 
    } 
+0

你有沒有考慮使用告警管理器或作業調度程序? – HaroldSer

回答

0

AlaraManager定期爲您執行您的任務。 就像這樣使用它。

public void scheduleAlarm(View v) 
    { 
     //set time here 
     Long time = new GregorianCalendar().getTimeInMillis()+24*60*60*1000; 

     // Create an Intent and set the class that will execute when the Alarm triggers.   
     Intent intentAlarm = new Intent(this, AlarmReceiver.class); 

     // onReceive() method of this class will execute when the broadcast from your alarm is received. 

     // Get the Alarm Service 
     AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE); 

     // Set the alarm for a particular time. 
     alarmManager.set(AlarmManager.RTC_WAKEUP, time, PendingIntent.getBroadcast(this, 1, intentAlarm, PendingIntent.FLAG_UPDATE_CURRENT)); 
     Toast.makeText(this, "Alarm Scheduled for Tommrrow", Toast.LENGTH_LONG).show();  
    } 

AlarmReceiver類

public class AlarmReceiver extends BroadcastReceiver 
{ 
    @Override 
    public void onReceive(Context context, Intent intent) 
    { 

     //perform what ever the operation you want 
     //when alarm triggers daily on your time 

    } 
} 
+0

你也可以使用TimerTask來做到這一點,但是它在某些設備上不能正常工作,並且如果需要空間,系統會在一段時間後被系統殺死。 – Radhey

相關問題