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

Android 31+版本FLAG_IMMUTABLE/FLAG_MUTABLE PendingIntent错误求助

问题分析与解决方案

从错误栈可以看出,问题并非来自你自己写的PendingIntent.getActivity()调用,而是AndroidX WorkManager库内部在创建广播类型的PendingIntent时,没有针对Android 12(API 31+)设置必需的FLAG_IMMUTABLE或FLAG_MUTABLE标记。

解决方法

1. 升级AndroidX WorkManager到兼容版本(推荐)

WorkManager在2.7.0及以上版本已经修复了这个适配问题,会自动为API 31+的设备添加正确的PendingIntent标记。在你的项目build.gradle(Module级别)中更新依赖:

dependencies {
    // 替换为最新稳定版,例如2.8.1或更高
    implementation "androidx.work:work-runtime:2.8.1"
}

2. 手动配置WorkManager的PendingIntent标记(无法升级库时使用)

如果暂时不能升级WorkManager,可以在Application初始化时,手动指定PendingIntent的标记:

Kotlin代码示例:

class MyApplication : Application() {
    override fun onCreate() {
        super.onCreate()
        val pendingIntentFlags = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            PendingIntent.FLAG_IMMUTABLE
        } else {
            0 // 低版本无需设置
        }
        val config = Configuration.Builder()
            .setPendingIntentFlags(pendingIntentFlags)
            .build()
        WorkManager.initialize(this, config)
    }
}

Java代码示例:

public class MyApplication extends Application {
    @Override
    public void onCreate() {
        super.onCreate();
        int pendingIntentFlags = Build.VERSION.SDK_INT >= Build.VERSION_CODES.S ? 
            PendingIntent.FLAG_IMMUTABLE : 0;
        Configuration config = new Configuration.Builder()
            .setPendingIntentFlags(pendingIntentFlags)
            .build();
        WorkManager.initialize(this, config);
    }
}

注意:确保你的Application类已经在AndroidManifest.xml中注册。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 22:23:14