我试图添加一些"提醒"我的应用程序的功能。我想设置AlarmManager
并在闹钟发生时触发Notification
。
我添加了一些方法来创建闹钟,取消闹钟,并查看闹钟是否处于活动状态。
以下代码位于Settings.class
Activity
:
private boolean getRemindersEnabled() {
return (PendingIntent.getBroadcast(this,
1,
new Intent(this, Main.class),
PendingIntent.FLAG_NO_CREATE) != null);
}
private void enableReminders() {
AlarmManager alarmMgr;
PendingIntent alarmIntent;
alarmMgr = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(this, Main.class);
alarmIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, mDayStart);
calendar.set(Calendar.MINUTE, 0);
alarmMgr.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
SIXY_MINUTES,
alarmIntent);
mRemindersEnabled = getRemindersEnabled();
populateReminders();
}
private void disableReminders() {
AlarmManager service = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(this, Main.class);
PendingIntent pending = PendingIntent.getBroadcast(this,
0,
intent,
PendingIntent.FLAG_CANCEL_CURRENT);
service.cancel(pending);
mRemindersEnabled = getRemindersEnabled();
populateReminders();
}
当我拨打enableReminders()
时,它会发出警报。但是,getRemindersEnabled()
返回false。我有什么不能做的吗?
答案 0 :(得分:0)
getRemindersEnabled()
应使用与创建警报的requestCode
相同的PendingIntent
。在这种情况下,您使用的是1
,正确的将是0
。
private boolean getRemindersEnabled() {
return (PendingIntent.getBroadcast(this,
0,
new Intent(this, Main.class),
PendingIntent.FLAG_NO_CREATE) != null);
}
<强> [编辑] 强>
要在致电service.cancel(intent);
之前取消闹钟,请使用旗帜pending.cancel();
FLAG_UPDATE_CURRENT
PendingIntent pending = PendingIntent.getBroadcast(this,
0,
intent,
PendingIntent. FLAG_UPDATE_CURRENT);
pending.cancel();
service.cancel(pending);