【发布时间】:2013-12-10 20:10:56
【问题描述】:
我正在使用 AlarmManager 来安排 1 到 35 个警报之间的任意位置(取决于用户输入)。当用户请求安排新警报时,我需要取消当前警报,因此我使用相同的 requestCode 创建所有警报,在 final 变量中定义。
// clear remaining alarms
Intent intentstop = new Intent(this, NDService.class);
PendingIntent senderstop = PendingIntent.getService(this,
NODIR_REQUESTCODE, intentstop, 0);
am.cancel(senderstop);
// loop through days
if (sched_slider.getBooleanValue())
for (int day = 1; day < 8; day++) {
if (day == 1 && sun.isChecked())
scheduleDay(day);
if (day == 2 && mon.isChecked())
scheduleDay(day);
if (day == 3 && tue.isChecked())
scheduleDay(day);
if (day == 4 && wed.isChecked())
scheduleDay(day);
if (day == 5 && thu.isChecked())
scheduleDay(day);
if (day == 6 && fri.isChecked())
scheduleDay(day);
if (day == 7 && sat.isChecked())
scheduleDay(day);
}
...
public void scheduleDay(int dayofweek) {
Intent toolintent = new Intent(this, NDService.class);
toolintent.putExtra("TOOL", "this value changes occasionally");
PendingIntent pi = PendingIntent.getService(this,
NODIR_REQUESTCODE, toolintent, 0);
calendar.set(Calendar.DAY_OF_WEEK, dayofweek);
calendar.set(Calendar.HOUR_OF_DAY, hour);
calendar.set(Calendar.MINUTE, minute);
calendar.set(Calendar.SECOND, 0);
am.setRepeating(AlarmManager.RTC, calendar.getTimeInMillis(),
AlarmManager.INTERVAL_DAY * 7, pi);
}
在这里,如果用户选中了sun(这是一个复选框),它将安排在每个星期日在hour 和minute 运行警报。您可以看到以这种方式创建的每个警报都有相同的 requestCode,但 TOOL 的额外更改有时会针对每个警报。
但是,在我的测试中,当警报响起并且我的服务运行时,Intent 中的额外内容现在是 null。 This question 建议使用 PendingIntent.FLAG_CANCEL_CURRENT 可以解决这个问题,但那不会取消其他 PendingIntents 吗?
简而言之:
有人能解释一下 PendingIntents 是如何工作的吗?关于创建多个具有相同 requestCode 和不同附加项的内容?我应该使用哪些标志(如果有)?
【问题讨论】:
标签: android alarmmanager android-pendingintent