检查警报管理器是否 运行(未正常工作)

Check if an alarm manager is running (not working correctly)

首先我确实阅读了与此类似的其他问题,似乎最有帮助的是这个 one,并尝试使用前两个答案来解决我的问题,我在主要 activity 如图所示

private static final int NOTIFICATION_REMINDER_PROMPT = 0;
private static final int NOTIFICATION_REMINDER_UPDATE = 1;

if(!alarmIsRunning(this, new Intent(this, PromptReceiver.class))) {

    Intent notifyIntent = new Intent(this, PromptReceiver.class);
    PendingIntent pendingIntent = PendingIntent.getBroadcast
            (this, NOTIFICATION_REMINDER_PROMPT, notifyIntent, PendingIntent.FLAG_UPDATE_CURRENT);
    AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),
            1000 * 60 * 60, pendingIntent);

}

if(!alarmIsRunning(this, new Intent(this, UpdateReceiver.class))) {
    Intent notifyIntent2 = new Intent(this, UpdateReceiver.class);
    PendingIntent pendingIntent2 = PendingIntent.getBroadcast
            (this, NOTIFICATION_REMINDER_UPDATE, notifyIntent2, PendingIntent.FLAG_UPDATE_CURRENT);
    AlarmManager alarmManager2 = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    alarmManager2.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),
            1000 * 60 * 60 * 50, pendingIntent2);
}

另外if函数中使用的函数代码如下

public static boolean alarmIsRunning(Context context, Intent intent){
    return PendingIntent.getBroadcast(context, 0,
            intent, PendingIntent.FLAG_NO_CREATE) != null;
}

现在我的问题是,当我调试时,第一个 if 条件总是给出 true,第二个总是给出 false 并运行里面的代码,但是当我使用第二种方法时 adb shell dumpsys alarm 行,只有第二行在工作。这个好像有点不明白

当您获取一个挂起的意图以查看它是否存在时,您需要完全按照以前的方式重新创建它。因此,您需要将原始请求代码传递给 alarmIsRunning() 方法。

这里摘自其中一种方法供参考:

private fun doesPendingIntentExist(requestCode: Int, intent: Intent): Boolean {
    val tempPendingIntent = PendingIntent.getBroadcast(context,
            requestCode, intent,
            PendingIntent.FLAG_NO_CREATE)
    tempPendingIntent?.cancel()
    return tempPendingIntent != null
}

TL;DR:需要将原始请求码传给PendingIntent.getBroadcast()方法