如何检查警报是否没有未决意图?

How to check if alarm does not have a pending intent?

在我拨打 schedulePing 之后,我的闹钟会在设定的时间段触发。使用 pingScheduled 我可以查看是否存在未决意图。但是,如果我用 cancelPing 取消警报,pingScheduled 仍然 return 为真。

  fun schedulePing(context: Context) {
    val am = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
    val intent = Intent(context, EventReceiver::class.java)
    intent.action = EventReceiver.PING
    val pendingIntent = PendingIntent.getBroadcast(context, PING, intent,
        PendingIntent.FLAG_CANCEL_CURRENT)
    val s = SettingsUtil.load(context)
    am.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
        SystemClock.elapsedRealtime() + s.periodPing, s.periodPing,
        pendingIntent)
  }

  fun cancelPing(context: Context) {
    if (pingScheduled(context).not()) return
    val am = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
    val intent = Intent(context, EventReceiver::class.java)
    intent.action = EventReceiver.PING
    val pendingIntent = PendingIntent.getBroadcast(context, PING, intent,
        PendingIntent.FLAG_CANCEL_CURRENT)
    am.cancel(pendingIntent)

  }

  fun pingScheduled(context: Context): Boolean {
    val intent = Intent(context, EventReceiver::class.java)
    intent.action = EventReceiver.PING
    return PendingIntent.getBroadcast(context, PING,
        intent, PendingIntent.FLAG_NO_CREATE) != null
  }

am.cancel(pendingIntent) 取消 alram,但不丢弃挂起的 intent。所以打电话很重要 pendingIntent.cancelam.cancel 之后可以使用 PendingIntent.FLAG_NO_CREATE

检查正确的存在