应用运行时FCM推送无响应,能否用NotificationManager显示通知?
解决FCM前台不显示通知的问题
当然可以!当应用处于前台时,FCM不会自动帮你弹出通知,这时候就需要我们手动通过NotificationManager来创建并显示通知,下面是具体的实现方案:
核心原理
FCM的推送消息分为两种类型:
- 通知消息:应用后台时系统自动展示,前台时会触发
OnMessageReceived但不会自动弹通知 - 数据消息:无论前后台都会触发
OnMessageReceived,需要开发者自行处理展示逻辑
你的场景正好需要在前台时手动处理通知展示,用NotificationManager完全可行。
完整代码实现
在你的MyFirebaseMessagingService类中,补充OnMessageReceived的逻辑:
[IntentFilter(new[] { "com.google.firebase.MESSAGING_EVENT" })] public class MyFirebaseMessagingService : FirebaseMessagingService { public override void OnMessageReceived(RemoteMessage message) { base.OnMessageReceived(message); // 提取推送内容(根据你的消息结构调整) string title = message.Notification?.Title ?? message.Data.TryGetValue("title", out var t) ? t : "默认标题"; string body = message.Notification?.Body ?? message.Data.TryGetValue("body", out var b) ? b : "默认内容"; // 调用显示通知的方法 ShowForegroundNotification(title, body); } private void ShowForegroundNotification(string title, string body) { // 1. 创建通知渠道(Android 8.0及以上必须) string channelId = "fcm_default_channel"; string channelName = "FCM通知"; string channelDescription = "接收FCM推送通知"; if (Build.VERSION.SdkInt >= BuildVersionCodes.O) { var channel = new NotificationChannel(channelId, channelName, NotificationImportance.Default) { Description = channelDescription }; // 获取NotificationManager实例 var notificationManager = GetSystemService(NotificationService) as NotificationManager; notificationManager?.CreateNotificationChannel(channel); } // 2. 构建通知内容 var intent = PackageManager.GetLaunchIntentForPackage(PackageName); intent.AddFlags(ActivityFlags.ClearTop); var pendingIntent = PendingIntent.GetActivity(this, 0, intent, PendingIntentFlags.UpdateCurrent | PendingIntentFlags.Immutable); var notificationBuilder = new NotificationCompat.Builder(this, channelId) .SetSmallIcon(Resource.Drawable.ic_notification) // 替换成你的通知图标 .SetContentTitle(title) .SetContentText(body) .SetAutoCancel(true) .SetContentIntent(pendingIntent); // 3. 显示通知 var notificationManagerCompat = NotificationManagerCompat.From(this); notificationManagerCompat.Notify(1, notificationBuilder.Build()); } }
注意事项
- 权限配置:Android 13及以上需要在
AndroidManifest.xml中添加POST_NOTIFICATIONS权限:<uses-permission android:name="android.permission.POST_NOTIFICATIONS" /> - 通知图标:确保你的项目中有对应的通知图标资源,否则会显示系统默认图标
- PendingIntentFlags:Android 12及以上需要使用
PendingIntentFlags.Immutable或Mutable,避免兼容性问题 - 通知ID:
Notify方法的第一个参数是通知ID,如果你想每次推送都显示新通知,可以用唯一ID(比如时间戳),如果想覆盖之前的通知用固定ID
这样修改后,无论应用处于前台还是后台,都能正常显示推送通知啦!
内容的提问来源于stack exchange,提问作者user3471528
相关产品推荐
相关产品推荐

