如何检查AlarmManager是否具有FLAG_ONE_SHOT设置的警报

时间:2015-01-04 08:04:37

标签: android alarmmanager android-pendingintent

如果我使用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按预期返回非空。

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

2 个答案:

答案 0 :(得分:0)

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

你每天都学到新东西: - )

要解决您的问题,我会删除FLAG_ONE_SHOT因为您可能不需要它(只需将0作为&#34; flags&#34;参数)。如果您多次设置闹钟,如果您每次都设置不同的额外闹钟,则可以使用FLAG_UPDATE_CURRENT(但看起来您没有使用任何其他内容,所以您可能不会需要这个)。我不认为你需要FLAG_ONE_SHOT来做你想做的事。

答案 1 :(得分:0)

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

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

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

我不认为涉及警报。