服务在特定时间Android上运行

时间:2013-11-23 06:18:59

标签: android android-intent android-service alarmmanager android-alarms

我正在尝试每天只在特定时间运行服务, 我们每天早上8点说

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

1 个答案:

答案 0 :(得分: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.INTERVAL_DAY

  

24 * 60 * 60 * 1000

。这意味着在24小时后重复报警