1

我想每天只在特定時間運行服務運行, 讓說,每天8:00 ,在這裏我找到了兩種方法服務於特定時間的Android

public static void setScheduleMessage(Context context, int hours, 
     int minuts, int seconds) { 
    Calendar calendar = Calendar.getInstance(); 
    // 8 AM 
    calendar.set(Calendar.HOUR_OF_DAY, hours); 
    calendar.set(Calendar.MINUTE, minuts); 
    calendar.set(Calendar.SECOND, seconds); 
    PendingIntent pendingIntent = PendingIntent.getService(context, 0, 
      new Intent(context, MessageSchduledService.class), 
      PendingIntent.FLAG_UPDATE_CURRENT); 
    AlarmManager alarmManager = (AlarmManager) context 
      .getSystemService(Context.ALARM_SERVICE); 
    alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, 
      calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, 
      pendingIntent); 
} 

但問題此方法是指定時間後每小時運行一次。

這裏是第二種方法,我用它不執行我的服務?

public static void setScheduleMessage2(Context context, int hours, 
     int minuts, int seconds) { 
    Calendar cur_cal = new GregorianCalendar(); 
    cur_cal.setTimeInMillis(System.currentTimeMillis());// set the current 

    // time and date for 

    // this calendar 
    Calendar cal = new GregorianCalendar(); 
    cal.add(Calendar.DAY_OF_YEAR, cur_cal.get(Calendar.DAY_OF_YEAR)); 
    cal.set(Calendar.HOUR_OF_DAY, hours); 
    cal.set(Calendar.MINUTE, minuts); 
    cal.set(Calendar.SECOND, cur_cal.get(Calendar.SECOND)); 
    cal.set(Calendar.MILLISECOND, cur_cal.get(Calendar.MILLISECOND)); 
    cal.set(Calendar.DATE, cur_cal.get(Calendar.DATE)); 
    cal.set(Calendar.MONTH, cur_cal.get(Calendar.MONTH)); 
    Intent intent = new Intent(context, MessageSchduledService.class); 

    PendingIntent pintent = PendingIntent.getService(context, 0, intent, 0); 
    AlarmManager alarm = (AlarmManager) context 
      .getSystemService(Context.ALARM_SERVICE); 

    alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), 
      AlarmManager.INTERVAL_DAY, pintent); 

} 

POST: 在我的應用我只是想從我的應用程序數據庫進行信息數據的基礎上,在特定的時間,每天推送消息。 如果有人對此有所瞭解,那麼讓我知道我在這些方法中做錯了什麼?

回答

3

看一看Alarms
@ RTC例子

// Set the alarm to start at approximately 2:00 p.m. 
Calendar calendar = Calendar.getInstance(); 
calendar.setTimeInMillis(System.currentTimeMillis()); 
calendar.set(Calendar.HOUR_OF_DAY, 14); 

// With setInexactRepeating(), you have to use one of the AlarmManager interval 
// constants--in this case, AlarmManager.INTERVAL_DAY. 
alarmMgr.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 
     AlarmManager.INTERVAL_DAY, alarmIntent); 

在你的代碼

alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), 
      AlarmManager.INTERVAL_DAY, pintent); 

更換

AlarmManager.INT ERVAL_DAY

24 * 60 * 60 * 1000

。這意味着在24小時後準確地重複報警

+0

感謝Vinay,我還有一個問題,假設我設置每天超過報警。然後我重新啓動我的設備,那麼它是否仍然每天都會報警?或者我需要啓動完整的廣播並再次設置鬧鐘? – khurram

+1

需要開機完成廣播並重新設置鬧鐘,可以節省共享首選時間。 – vinaykumar

+0

所以如果使用setInexactRepeating(),你不能指定一個自己的時間,而是必須使用區間常量? – Mafro34

相關問題