如何每天启动AlarmService

时间:2016-02-25 08:37:57

标签: android alarmmanager

我有一个AlarmService,在devicve启动时初始化,从早上6点开始,到下午6点结束,每小时重复一次。 在下午6点取消后,如何确保它再次启动?

这是我的BootReceiver:

if (intent.getAction().equals("android.intent.action.BOOT_COMPLETED")) {
    // assign RefreshService class
    Intent alarmIntent = new Intent(context, RefreshService.class);
    PendingIntent alarmPendingIntent = PendingIntent.getBroadcast(context, alarmManagerRequestCode, alarmIntent, 0);
    // set the alarm
    // it starts at 6 am and repeats once an hour
    // elapsed_realtime is used to save ressources
    AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        alarmManager.setInexactRepeating(AlarmManager.ELAPSED_REALTIME,                    firstRefresh,
            AlarmManager.INTERVAL_HOUR,
            alarmPendingIntent);
}

因此,当设备启动并在早上6点(firstRefresh)启动并按小时重复时,它会被初始化。 要让它停止,我会将以下内容放入我的RefreshService(lastRefresh是下午6点,以毫秒为单位):

if (System.currentTimeMillis() >= lastRefresh) {
        Intent alarmIntent = new Intent(this, RefreshService.class);
        PendingIntent alarmPendingIntent = PendingIntent.getBroadcast(this, BootReceiver.alarmManagerRequestCode, alarmIntent, 0);
        AlarmManager alarmManager = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
        alarmManager.cancel(alarmPendingIntent);
}

感谢所有人的帮助!

3 个答案:

答案 0 :(得分:0)

感谢@Opiatefuchs指出:

您唯一需要做的就是在取消闹钟后设置闹钟并将第一次闹钟设置为第二天所需的时间。

答案 1 :(得分:-1)

为此使用日历,AlarmManager和pendingIntent -

Calendar calendar = Calendar.getInstance();

calendar.set(Calendar.HOUR_OF_DAY, 5); // For 5 AM or 6 AM
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
 PendingIntent pi = PendingIntent.getService(context, 0,
        new Intent(context, NewClass.class),PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
am.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
                            AlarmManager.INTERVAL_DAY, pi);

答案 2 :(得分:-1)

使用setRepeating

这是一个很好的例子: https://stackoverflow.com/a/13879448/4617458