.NET MAUI Android Firebase服务OnMessageReceived执行异常求助
检查
data集合遍历逻辑
Firebase RemoteMessage的Data字典可能存在平台层的特殊处理,直接遍历data.Keys可能触发隐式异常。建议先将其转为本地集合再遍历,避免集合状态异常:// 替换原foreach代码 var localData = new Dictionary<string, string>(data); foreach (var key in localData.Keys) { var value = localData[key]; intent.PutExtra(key, value); }排查
PendingIntent创建的兼容性问题
你使用的PendingIntentFlags.OneShot | PendingIntentFlags.Immutable组合在部分Android版本上可能存在兼容性问题,尤其是当MainActivity.NotificationId重复时。可以单独拆分这部分代码并添加日志:try { var pendingIntent = PendingIntent.GetActivity(this, MainActivity.NotificationId, intent, PendingIntentFlags.OneShot | PendingIntentFlags.Immutable); } catch (Exception ex) { Android.Util.Log.Error("NotificationError", $"PendingIntent创建失败: {ex.Message}"); }验证通知图标资源有效性
Microsoft.Maui.Controls.Resource.Drawable.ic_notification如果不存在或路径错误,Android会静默中断通知创建流程(不抛出C#层异常)。确保该图标文件存在于Android项目的Resources/drawable目录,文件名和大小写完全匹配。查看Android系统日志(Logcat)
部分系统级异常不会被C#的try-catch捕获,需要过滤应用包名或NotificationManager关键词,查找类似Failed to post notification的错误信息,定位系统层面的失败原因。确认通知渠道已正确创建
Android 8.0及以上版本必须创建通知渠道才能显示通知,若MainActivity.ChannelId对应的渠道未初始化,Notify方法会静默失败。在MainActivity的OnCreate中添加渠道创建代码:if (Build.VERSION.SdkInt >= BuildVersionCodes.O) { var channel = new NotificationChannel(MainActivity.ChannelId, "通知渠道名称", NotificationImportance.Max) { Description = "渠道描述信息" }; var notificationManager = GetSystemService(NotificationService) as NotificationManager; notificationManager?.CreateNotificationChannel(channel); }
内容的提问来源于stack exchange,提问作者Wasyster

