Xamarin Android中如何将Firebase PendingIntent声明为不可变?
解决方案:Android 12+ 下 Firebase 推送 PendingIntent 异常处理
问题核心
当应用目标版本升级到 Android 12(API 31)及以上时,系统强制要求创建PendingIntent时必须指定FLAG_IMMUTABLE或FLAG_MUTABLE标志,否则会抛出Java.Lang.IllegalArgumentException异常。旧版本 Firebase 相关库未适配该规则,导致推送流程报错。
具体修复步骤
1. 升级 Firebase NuGet 包到兼容版本
确保你使用的Xamarin.Firebase.Messaging、Xamarin.Firebase.Core等 NuGet 包是支持 Android 12+ 的最新版本。官方新版本库已内置修复,会自动为内部创建的PendingIntent添加必要标志。
2. 手动修复自定义通知的 PendingIntent 代码
如果升级包后问题仍存在,或需要自定义通知逻辑,在创建PendingIntent时手动添加版本适配的标志:
- 普通推送场景优先使用
PendingIntentFlags.Immutable - 若需支持内回复、气泡功能,使用
PendingIntentFlags.Mutable
示例代码(C# Xamarin):
// 创建启动主页面的Intent Intent intent = new Intent(this, typeof(MainActivity)); intent.AddFlags(ActivityFlags.ClearTop); // 根据Android版本适配PendingIntent标志 var pendingIntentFlags = Build.VERSION.SdkInt >= BuildVersionCodes.S ? PendingIntentFlags.Immutable : PendingIntentFlags.UpdateCurrent; var pendingIntent = PendingIntent.GetActivity(this, 0, intent, pendingIntentFlags); // 构建并发送通知 NotificationCompat.Builder builder = new NotificationCompat.Builder(this, "your_channel_id") .SetSmallIcon(Resource.Drawable.ic_notification) .SetContentTitle(messageTitle) .SetContentText(messageBody) .SetAutoCancel(true) .SetContentIntent(pendingIntent); NotificationManager notificationManager = (NotificationManager)GetSystemService(Context.NotificationService); notificationManager.Notify(0, builder.Build());
3. 检查清单文件服务配置
确保FirebaseMessagingService的清单配置正确,同时建议废弃旧版FirebaseInstanceIdService(已被官方标记为过时):
<!-- 正确配置FirebaseMessagingService --> <service android:name=".MyFirebaseMessagingService"> <intent-filter> <action android:name="com.google.firebase.MESSAGING_EVENT" /> </intent-filter> </service> <!-- 旧版InstanceIdService建议删除,功能迁移到FirebaseMessaging.OnNewToken --> <!-- <service android:name=".MyFirebaseIIDService"> <intent-filter> <action android:name="com.google.firebase.INSTANCE_ID_EVENT" /> </intent-filter> </service> -->
4. 迁移旧版 Token 刷新逻辑到新 API
原FirebaseInstanceIdService的OnTokenRefresh方法已被废弃,将 Token 刷新逻辑迁移到FirebaseMessagingService的OnNewToken方法:
public class MyFirebaseMessagingService : FirebaseMessagingService { // 处理推送消息 public override void OnMessageReceived(RemoteMessage message) { base.OnMessageReceived(message); // 自定义消息处理逻辑 } // 替代原OnTokenRefresh,获取新设备Token public override void OnNewToken(string token) { base.OnNewToken(token); // 保存或上传Token到服务器的逻辑 } }
验证
将应用目标版本设置为 Android 12+,重新编译运行,测试 Firebase 推送通知,确认异常不再抛出。
内容的提问来源于stack exchange,提问作者sumit
相关产品推荐
相关产品推荐

