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
相关产品推荐
相关产品推荐

