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

时间:2018-01-10 10:25:58

标签: android android-alarms

在我拨打schedulePing后,我的闹钟会在设定的时间内触发。使用pingScheduled,我可以看到是否存在待处理意图。但是,如果我使用cancelPing取消闹钟,pingScheduled仍会返回true。

  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
  }

1 个答案:

答案 0 :(得分:0)

am.cancel(pendingIntent)取消alram,但不会丢弃待处理的意图。所以打电话很重要 pendingIntent.cancel之后的am.cancel能够使用PendingIntent.FLAG_NO_CREATE

检查正确的状态