You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android Kotlin通知存在性检查始终返回true的原因排查

问题原因与解决方案

核心问题

checkAlarm方法在Android 8.0(API 26)及以上版本中缺少PendingIntent.FLAG_NO_CREATE标记,导致系统会自动创建新的PendingIntent,而非仅检查是否已存在,最终让checkAlarm始终返回true。

具体分析

  • PendingIntent.FLAG_NO_CREATE的作用是:当不存在匹配的PendingIntent时,返回null,而不是创建新的实例。
  • 在你的checkAlarm代码中,Android O+版本只传入了FLAG_IMMUTABLE,没有结合FLAG_NO_CREATE。此时调用PendingIntent.getBroadcast(),系统会直接创建一个符合条件的PendingIntent并返回——无论之前是否调用过setAlarm,返回值都不会是null,所以checkAlarm永远返回true。

修复代码

修改checkAlarm中的flags逻辑,将FLAG_NO_CREATE与FLAG_IMMUTABLE组合使用:

fun checkAlarm(context: Context): Boolean {
    val alarmIntent = Intent(context, NotifierReceiver::class.java)
    alarmIntent.action = ACTION_BD_NOTIFICATION

    val intFlags = if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
        // 同时添加FLAG_NO_CREATE和FLAG_IMMUTABLE
        PendingIntent.FLAG_NO_CREATE or PendingIntent.FLAG_IMMUTABLE
    } else {
        PendingIntent.FLAG_NO_CREATE
    }

    return PendingIntent.getBroadcast(
        context, notificationId,
        alarmIntent,
        intFlags
    ) != null
}

额外验证点

确保notificationId在checkAlarm和setAlarm方法中是同一个常量值,因为PendingIntent的匹配规则包含requestCode(即这里的notificationId),如果两者id不一致,也会导致判断逻辑失效。

内容的提问来源于stack exchange,提问作者Marduk

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 22:30:17