在我拨打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
}
答案 0 :(得分:0)
am.cancel(pendingIntent)
取消alram,但不会丢弃待处理的意图。所以打电话很重要
pendingIntent.cancel
之后的am.cancel
能够使用PendingIntent.FLAG_NO_CREATE