我试图每天仅在特定时间运行服务,
可以说每天上午8:00
在这里,我发现了两种方法

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:
在我的应用程序中,我只想每天在特定时间将消息从应用程序数据库推送到消息数据库。
如果有人对此有任何想法,请让我知道我在这些方法中做错了什么?

最佳答案

看看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.INTERVAL_DAY





  24 * 60 * 60 * 1000


。这意味着要在24小时后再次发出警报

08-18 11:20