为Android 12通知添加回复功能时遇PendingIntent可变错误
解决Android通知回复功能的PendingIntent可变要求错误
你在为Android应用添加通知回复功能时遇到以下错误:
PendingIntents attached to actions with remote inputs must be mutable
错误原因
从Android 12(API 31)开始,与包含RemoteInput的通知操作绑定的PendingIntent必须是可变的(Mutable)——系统需要将用户输入的回复内容写入Intent中,而你当前在Android 11及以上版本中使用了FLAG_IMMUTABLE,导致系统无法修改Intent数据,触发报错。
修复方案
1. 修改PendingIntent创建逻辑
移除FLAG_IMMUTABLE,并在Android 12及以上版本显式指定FLAG_MUTABLE,确保PendingIntent允许系统修改其携带的Intent数据。
修改后的代码:
PendingIntent replyPendingIntent; int flags = PendingIntent.FLAG_UPDATE_CURRENT; // Android 12及以上版本必须设置FLAG_MUTABLE if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { flags |= PendingIntent.FLAG_MUTABLE; } replyPendingIntent = PendingIntent.getActivity( getApplicationContext(), channel.uuid.hashCode(), replyIntent, flags );
2. (可选)迁移到AndroidX依赖
你当前使用的com.android.support:support-compat:28.0.0属于已停止维护的旧版Support库,建议迁移到AndroidX以获得更好的兼容性和后续更新:
将app/build.gradle中的依赖替换为:
dependencies { implementation 'androidx.core:core:1.10.1' // 可替换为最新版本 implementation 'androidx.work:work-runtime-ktx:2.7.1' implementation 'androidx.preference:preference-ktx:1.2.0' }
内容的提问来源于stack exchange,提问作者Khader Murtaja
相关产品推荐
相关产品推荐

