Xamarin Forms安卓端应用关闭时推送通知显示异常求助
Android端Xamarin应用关闭时推送通知仅显示Body的解决方案
问题现象
- iOS端推送通知接收、显示均正常
- Android应用处于前台时,推送通知触发及显示符合预期
- Android应用关闭/后台时,推送通知仅显示
body字段内容,无标题或自定义配置项 - 推送由ASP.NET Core通过Azure Notification Hub发送,当前Payload构造代码:
new JObject(new JProperty("notification", pushMessage)).ToString(Formatting.None)
核心原因
Android在应用关闭/后台状态下,系统会直接通过Firebase Cloud Messaging(FCM)的系统通道处理推送,而非走App自定义逻辑。若仅使用统一的notification类型Payload,Azure Notification Hub对Android字段的自动映射可能不完整,导致仅body被系统识别。
解决方案
方案1:针对Android平台配置专属通知字段
发送推送时,为Android单独指定完整的通知参数,确保系统能正确解析所有字段:
var payload = new JObject( // 通用通知字段(适配iOS) new JProperty("notification", new JObject( new JProperty("title", "通用通知标题"), new JProperty("body", "通用通知内容") )), // Android专属配置 new JProperty("android", new JObject( new JProperty("notification", new JObject( new JProperty("title", "Android专属标题"), new JProperty("body", "Android专属内容"), new JProperty("channel_id", "your_notification_channel_id") // Android 8.0+ 必填 )) )) ).ToString(Formatting.None);
方案2:使用data类型Payload,由App自定义处理
若需要完全控制通知显示逻辑,推荐使用data字段传递内容,即使应用关闭,FCM也会将数据传递到App的FirebaseMessagingService,由你自行构建通知:
1. 构造data类型Payload
var payload = new JObject( new JProperty("data", new JObject( new JProperty("title", "自定义通知标题"), new JProperty("body", "自定义通知内容"), new JProperty("custom_data", "额外业务数据") )) ).ToString(Formatting.None);
2. 实现Firebase消息服务子类
在Xamarin Android项目中创建FirebaseMessagingService子类,重写OnMessageReceived方法构建通知:
[Service] [IntentFilter(new[] { "com.google.firebase.MESSAGING_EVENT" })] public class CustomFirebaseMessagingService : FirebaseMessagingService { public override void OnMessageReceived(RemoteMessage message) { // 解析data字段内容 var title = message.Data["title"]; var body = message.Data["body"]; // 构建通知 var notificationBuilder = new NotificationCompat.Builder(this, "your_notification_channel_id") .SetContentTitle(title) .SetContentText(body) .SetSmallIcon(Resource.Drawable.ic_notification_icon) .SetAutoCancel(true); // 显示通知 var notificationManager = NotificationManagerCompat.From(this); notificationManager.Notify(0, notificationBuilder.Build()); } }
3. 初始化Android通知通道(Android 8.0+)
在App启动时创建通知通道,否则通知无法正常显示:
if (Build.VERSION.SdkInt >= BuildVersionCodes.O) { var channel = new NotificationChannel( "your_notification_channel_id", "推送通知通道", NotificationImportance.Default) { Description = "用于展示应用推送通知的通道" }; var notificationManager = GetSystemService(NotificationService) as NotificationManager; notificationManager?.CreateNotificationChannel(channel); }
额外检查项
- 确认Azure Notification Hub已正确配置Firebase服务器密钥(Android平台设置中)
- 确保设备已成功注册到Notification Hub,Token未过期
内容的提问来源于stack exchange,提问作者Nagarjuna Reddy
相关产品推荐
相关产品推荐

