Android 如何检查AlarmManager是否设置了带有“一次触发”标志的报警
如果我创建了一个带有FLAG_ONE_SHOT的PendingEvent,那么带有FLAG_NO_create的后续PendingEvent将返回nullAndroid 如何检查AlarmManager是否设置了带有“一次触发”标志的报警,android,alarmmanager,android-pendingintent,Android,Alarmmanager,Android Pendingintent,如果我创建了一个带有FLAG_ONE_SHOT的PendingEvent,那么带有FLAG_NO_create的后续PendingEvent将返回null AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); Intent intent = new Intent(context,AlarmService.class); PendingIntent pi = Pen
AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context,AlarmService.class);
PendingIntent pi = PendingIntent.getService(context,this.getId(),intent,PendingIntent.FLAG_ON_SHOT);
GregorianCalendar alarmtime = new GregorianCalendar(now.get(GregorianCalendar.YEAR),now.get(GregorianCalendar.MONTH),now.get(GregorianCalendar.DAY_OF_MONTH),0,0);
//Set the alarm
if (Build.VERSION.SDK_INT<Build.VERSION_CODES.KITKAT) {
am.set(AlarmManager.RTC_WAKEUP,alarmtime.getTimeInMillis(), pi);
} else {
am.setExact(AlarmManager.RTC_WAKEUP, alarmtime.getTimeInMillis(), pi);
}
//Now check if the alarm was set, if it was set, the following PendingIntent should return not null but it doesn't
PendingIntent piCheck = PendingIntent.getService(context,this.getId(),intent,PendingIntent.FLAG_NO_CREATE);
if (piCheck!=null) {
Log.d(TAG,"piCheck returned NOT NULL and probably returned pi");
} else if (piCheck==null) {
Log.d(TAG,"piCheck returned NULL pi does not exist");
然后,我的第二个PendingEvent按预期返回NOTNULL
两个悬挂式帐篷都正确设置了警报,但我无法“检查”悬挂式帐篷的旗帜。这种行为的原因是什么?它的目的是什么?我创建了一个小测试程序来验证这种行为。如果使用
标记一次
创建一个pendingent
,然后将其传递给AlarmManager
,看起来Android会立即“消费”该pendingent
,使其不再存在(因为它是“一次”,只能使用一次)。我本以为当警报真正触发时会发生这种情况,但事实并非如此
你每天都会学到新东西:-)
为了解决您的问题,我只需删除
标志\u ONE\u SHOT
,因为您可能不需要它(只需传递0
作为“flags”参数)。如果多次设置报警,如果每次都使用不同的附加设置报警,则可以使用FLAG\u UPDATE\u CURRENT
(但看起来您没有使用任何附加设置,因此您可能不需要此设置)。我不认为你需要FLAG_ONE_SHOT
来做你想做的事。这里出现的问题是因为FLAG_ONE_SHOT
描述了pendingent
,因此需要识别它。
您可以使用FLAG_ONE_SHOT | FLAG_NO_CREATE
检查它是否存在。
您的代码片段本质上是在检查一个不同的pendingent
(一个不带标志的
),它不存在,因此您会得到null
您也可以使用FLAG\u IMMUTABLE
来尝试这一点,这是另一个描述请求的pendingent
的标志
我认为这与警报无关。我想你一定是糊涂了。是什么让您认为使用flag
pendingent.flag\u NO\u CREATE
调用getService()
应该返回null
?只有当pendingent
不存在时,它才会返回null
。但是,您之前刚刚创建了pendingent
,因此它当然仍然存在。如果使用flagpendingent.flag\u CANCEL\u CURRENT
,我不知道为什么它会返回null
,因为这也会创建一个新的pendingent
。请解释一下。很抱歉把我的空和非空混淆了。使用标志_NO_CREATE,即使PendingEvent存在,它也将返回null。按预期标记取消当前工作。我仍然认为您感到困惑。如果使用FLAG_ONE_SHOT
创建pendingent
,则此pendingent只能使用一次。一旦使用,它将被删除。指定
FLAG\u CANCEL\u CURRENT`将永远不会返回null
,因为它将始终创建一个新的pendingent
。但是在创建任何一个pendingent之后,我都会有一个带有FLAG\u NO\u create的PI,如果该PI存在正确,则应该返回该PI?但它只返回标志“取消”当前PI,它从不返回一个快照PI(而是返回null)。这对我来说意味着PI不存在。但确实如此。它是用一个镜头创建的,但它仍然存在…我说得通吗?我需要自己测试一下。
PendingIntent pi = PendingIntent.getService(context,this.getId(),intent,PendingIntent.FLAG_CANCEL_CURRENT);