以下代码来自我的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服务类。当这个服务启动时,onHandleIntent()方法从我调用setWeeklyAlarms()方法的地方调用。现在我的问题是从这个方法内部我想根据我将从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);
}
}
答案 0 :(得分:1)
更改以下行:
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