我如何检查AlarmManager是否设置了带有FLAG_ONE_SHOT的警报

问题描述 投票:1回答:2

如果我创建带有FLAG_ONE_SHOT的PendingIntent,则后续带有FLAG_NO_CREATE的PendingIntent返回null。

    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");

但是,如果我将第一个待处理的意图更改为:

PendingIntent pi = PendingIntent.getService(context,this.getId(),intent,PendingIntent.FLAG_CANCEL_CURRENT);

然后我的第二个PendingIntent不按预期返回null。

两个PendingIntents都正确设置了警报,但是我无法“检查” FLAG_ONE_SHOT PendingIntent。这种行为的原因是什么?它的目的是什么?

android alarmmanager android-pendingintent
2个回答
0
投票

我创建了一个小型测试程序来验证此行为。如果您使用PendingIntent创建一个FLAG_ONE_SHOT,然后将其传递给AlarmManager,则看起来Android会立即“消费” PendingIntent,使其不再存在(因为它是“一次性”的),它只能使用一次)。我本以为在警报真正触发时会发生这种情况,但事实并非如此。

您每天都会学到一些新东西:-)

为了解决您的问题,我将删除FLAG_ONE_SHOT,因为您可能不需要它(只需将0作为“ flags”参数传递)。如果您多次设置了警报,则每次将警报设置为不同的附加功能时,可以使用FLAG_UPDATE_CURRENT(但是您似乎没有使用任何附加功能,因此您可能不需要此功能)。我认为您不需要尝试执行FLAG_ONE_SHOT


0
投票

这里出现问题是因为FLAG_ONE_SHOT 描述 PendingIntent,因此需要标识它。

您可以使用FLAG_ONE_SHOT | FLAG_NO_CREATE检查其存在。您的代码段实质上是在检查是否存在不存在的其他PendingIntent(没有FLAG_ONE_SHOT的一个),因此您会得到null

您也可以使用FLAG_IMMUTABLE进行尝试,这是另一个描述请求的PendingIntent的标志。

我不认为涉及警报。

© www.soinside.com 2019 - 2024. All rights reserved.