下面的代码来 self 的 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 服务类。当此服务启动时,从我调用 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 分钟,而不是 3 秒
关于java - 使用 AlarmManager 类从另一个警报内部设置警报未正确触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31623435/