You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Xamarin Forms Android端Firebase后台通知不弹出问题求助

解决Xamarin Forms Firebase推送Android后台通知不显示及PendingIntent标志错误

核心问题原因

Android 12(API 31)及以上版本要求创建PendingIntent时必须显式指定FLAG_IMMUTABLE或FLAG_MUTABLE标志,你的Firebase推送插件版本可能未适配该规则,导致后台通知服务崩溃,无法弹出通知。

解决方案

1. 升级Firebase Push Notification插件到最新版

旧版本插件通常没有处理Android 12+的PendingIntent标志要求,直接在NuGet管理器中搜索Plugin.FirebasePushNotification,安装最新稳定版本。更新后重新编译运行,多数情况下可直接解决该错误。

2. 自定义FirebaseMessagingService手动设置PendingIntent标志(升级后仍有问题时使用)

如果升级插件后问题依旧,可通过自定义消息服务来手动控制PendingIntent的创建:

步骤1:创建自定义MessagingService类

using Android.App;
using Android.Content;
using Android.OS;
using Firebase.Messaging;
using Plugin.FirebasePushNotification;

[Service]
[IntentFilter(new[] { "com.google.firebase.MESSAGING_EVENT" })]
public class CustomFirebaseMessagingService : FirebaseMessagingService
{
    public override void OnMessageReceived(RemoteMessage message)
    {
        base.OnMessageReceived(message);

        // 构建通知基础内容
        var notificationBuilder = new Notification.Builder(this, FirebasePushNotificationManager.DefaultNotificationChannelId)
            .SetContentTitle(message.GetNotification()?.Title ?? "通知")
            .SetContentText(message.GetNotification()?.Body ?? "新消息")
            .SetSmallIcon(Resource.Drawable.ic_notification) // 替换为你的通知图标
            .SetAutoCancel(true);

        // 创建跳转Intent并设置PendingIntent标志
        var intent = new Intent(this, typeof(MainActivity));
        intent.AddFlags(ActivityFlags.ClearTop);
        var pendingIntentFlags = Build.VERSION.SdkInt >= BuildVersionCodes.S 
            ? PendingIntentFlags.Immutable 
            : PendingIntentFlags.UpdateCurrent;
        var pendingIntent = PendingIntent.GetActivity(this, 0, intent, pendingIntentFlags);

        notificationBuilder.SetContentIntent(pendingIntent);

        // 显示通知
        var notificationManager = (NotificationManager)GetSystemService(NotificationService);
        notificationManager.Notify(0, notificationBuilder.Build());
    }
}

步骤2:在MainApplication中指定自定义服务

修改MainApplication的OnCreate方法,初始化时传入自定义服务类型:

#if DEBUG
FirebasePushNotificationManager.Initialize(this, true, customMessagingService: typeof(CustomFirebaseMessagingService));
#else
FirebasePushNotificationManager.Initialize(this, false, customMessagingService: typeof(CustomFirebaseMessagingService));
#endif

3. 确保Android项目依赖包更新

检查并更新所有相关的AndroidX和Google Play Services包,比如Xamarin.AndroidX.Core、Xamarin.GooglePlayServices.Base等,确保这些包的版本与Firebase插件版本兼容。

4. 处理Analytics库缺失警告

如果不需要Firebase Analytics,可忽略[FirebaseMessaging] Unable to log event: analytics library is missing警告;若需要该功能,在NuGet中安装Xamarin.Firebase.Analytics包即可消除警告。

内容的提问来源于stack exchange,提问作者hk77

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 20:24:50