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

Android12适配中PendingIntent.FLAG_IMMUTABLE在API23以下不可用问题

Android 12 PendingIntent 跨版本适配方案
  • 优先使用AndroidX兼容实现
    只要项目引入androidx.core:core:1.6.0及以上版本,可直接全局使用PendingIntent.FLAG_IMMUTABLE作为flag参数,无需额外版本判断。AndroidX已经对低版本系统做了兼容处理,不识别的flag位会被自动忽略,不会触发运行时异常。
    示例代码:
    PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_IMMUTABLE);
    
  • 非AndroidX项目适配方案
    手动添加版本分支判断,同时给低版本分支添加lint注解抑制告警即可。API 23以下系统本身没有PendingIntent可变性的限制,低版本分支不设置对应flag不会产生运行时问题。
    示例代码:
    PendingIntent pendingIntent;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_IMMUTABLE);
    } else {
        @SuppressLint("UnspecifiedImmutableFlag")
        pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);
    }
    
  • 特殊场景说明
    如果你的业务逻辑需要后续修改PendingIntent内含的Intent数据,请替换为PendingIntent.FLAG_MUTABLE,该常量同样在AndroidX 1.6.0+版本有兼容适配。注意Android 12及以上版本使用可变PendingIntent存在安全风险,非必要场景建议都用不可变类型。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 19:54:03