使用 AlarmManager class 从另一个警报内部设置警报未正确触发

Setting an alarm from inside another alarm using AlarmManager class not getting fired correctly

下面的代码来自我的 MainActivity onCreate() 方法,我在该方法中立即向 运行 服务 ScheduleAlarm 设置了一个警报,并且只设置一次。 sPrefs 是 SharedPreference 对象,它只负责设置此警报一次。服务 ScheduleAlarm 是一个被完美触发的 IntentService。

if(sPrefs.getBoolean("SettingAlarmForFirstTime",true)) {
        //Creating alarm for showing notifications.
        Calendar calendar = Calendar.getInstance();
        //calendar.setTimeInMillis(System.currentTimeMillis());
        //calendar.set(Calendar.HOUR_OF_DAY, 8);

        Intent intent = new Intent(MainActivity.this, ScheduleAlarms.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pendingIntent = PendingIntent.getService(this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
        AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
        alarmManager.set(AlarmManager.RTC, calendar.getTimeInMillis(), pendingIntent);//Use AlarmManager.INTERVAL_DAY instead of int number here.
        editor.putBoolean("SettingAlarmForFirstTime", false);
        editor.commit();
    }

现在这是我的 ScheduleAlarms 服务 class。当此服务启动时,从我调用 setWeeklyAlarms() 方法的地方调用 onHandleIntent() 方法。现在我的问题出在这个方法内部,我想根据从 API 服务器调用中获得的时间为整整一周设置 7 个警报。现在我什至无法完美地执行单个警报。我设置的警报设置为在 3 秒延迟后启动,这将调用另一个名为 NotificationService 的服务,但警报会立即触发,而不是等待 3 秒。请分析并告诉我为什么会这样。

public class ScheduleAlarms extends IntentService {
private boolean notificationsEnabled = true;
private String notificationTimings = "";

public ScheduleAlarms() {
    super("ScheduleAlarms");
}

@Override
protected void onHandleIntent(Intent intent) {
    setWeeklyAlarm();
}

private void setWeeklyAlarm() {
    Intent i = new Intent(ScheduleAlarms.this, NotificationService.class);
    i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    PendingIntent pendingIntent = PendingIntent.getService(ScheduleAlarms.this, 10001, i, 0);
    AlarmManager alarmManager = (AlarmManager) ScheduleAlarms.this.getSystemService(Context.ALARM_SERVICE);

/* 将此 alarmManager 设置为在延迟 3 分钟后触发警报,但此警报会立即触发*/

    alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, 3*60*1000, pendingIntent);


}

}

更改以下行:

alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, 3*60*1000, pendingIntent);

至:

alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, c.getTimeInMillis() + 3 * 60 * 1000, 3 * 60 * 1000, pendingIntent);

警报立即响起,因为

AlarmManager.ELAPSED_REALTIME_WAKEUP + 0, ...

因此,第一次,它在 0 秒后启动。要更改此设置,您需要在此处添加一些时间。

AlarmManager.ELAPSED_REALTIME_WAKEUP + time

而且,它也应该是重复的,所以你需要使用setRepeating

注:3 * 60 * 1000 == 3 minutes, not 3 seconds