求VS 2022中Xamarin.Forms集成Firebase Cloud Messaging的可用示例
Xamarin.Forms Firebase Cloud Messaging (FCM) 推送通知实现示例
前置准备
- 前往Firebase控制台创建项目,分别为Android、iOS平台配置应用,下载对应的
google-services.json(Android)和GoogleService-Info.plist(iOS)文件 - 确保Xamarin.Forms项目使用最新稳定版,安装对应平台的Firebase NuGet包
共享项目(Xamarin.Forms)
创建统一的推送服务接口,用于跨平台调用:
public interface IPushNotificationService { void Initialize(); Task<string> GetTokenAsync(); void SubscribeToTopic(string topic); }
在App.xaml.cs中初始化服务:
protected override void OnStart() { DependencyService.Get<IPushNotificationService>().Initialize(); }
Android 平台实现
- 将
google-services.json放在Android项目根目录,设置生成操作为GoogleServicesJson - 安装NuGet包:
Xamarin.Firebase.Messaging、Xamarin.GooglePlayServices.Base - 创建FCM消息处理服务类:
[Service] [IntentFilter(new[] { "com.google.firebase.MESSAGING_EVENT" })] public class MyFirebaseMessagingService : FirebaseMessagingService { public override void OnMessageReceived(RemoteMessage message) { base.OnMessageReceived(message); var title = message.GetNotification().Title; var body = message.GetNotification().Body; ShowNotification(title, body); } public override void OnNewToken(string token) { base.OnNewToken(token); Preferences.Set("FCM_Token", token); // 可将token上传至自有服务器 } private void ShowNotification(string title, string body) { var intent = new Intent(this, typeof(MainActivity)); intent.AddFlags(ActivityFlags.ClearTop); var pendingIntent = PendingIntent.GetActivity(this, 0, intent, PendingIntentFlags.OneShot); var notificationBuilder = new NotificationCompat.Builder(this, "default_channel") .SetContentTitle(title) .SetContentText(body) .SetSmallIcon(Resource.Drawable.ic_notification) .SetAutoCancel(true) .SetContentIntent(pendingIntent); var notificationManager = NotificationManager.FromContext(this); // Android 8.0+ 需创建通知渠道 if (Build.VERSION.SdkInt >= BuildVersionCodes.O) { var channel = new NotificationChannel("default_channel", "默认通知渠道", NotificationImportance.Default); notificationManager.CreateNotificationChannel(channel); } notificationManager.Notify(0, notificationBuilder.Build()); } }
- 在
MainActivity.cs中完成初始化:
protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); Xamarin.Essentials.Platform.Init(this, savedInstanceState); global::Xamarin.Forms.Forms.Init(this, savedInstanceState); FirebaseApp.InitializeApp(this); LoadApplication(new App()); } public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Android.Content.PM.Permission[] grantResults) { Xamarin.Essentials.Platform.OnRequestPermissionsResult(requestCode, permissions, grantResults); base.OnRequestPermissionsResult(requestCode, permissions, grantResults); }
- 实现共享项目的接口:
public class PushNotificationService : IPushNotificationService { public void Initialize() { // 初始化已在MainActivity完成 } public async Task<string> GetTokenAsync() { var token = await FirebaseMessaging.Instance.GetTokenAsync(); Preferences.Set("FCM_Token", token); return token; } public void SubscribeToTopic(string topic) { FirebaseMessaging.Instance.SubscribeToTopic(topic); } }
iOS 平台实现
- 将
GoogleService-Info.plist放在iOS项目根目录,设置生成操作为BundleResource - 安装NuGet包:
Xamarin.Firebase.iOS.Messaging、Xamarin.Firebase.iOS.Core - 在
AppDelegate.cs中配置推送:
using Firebase.Core; using Firebase.Messaging; using UserNotifications; namespace YourApp.iOS { [Register("AppDelegate")] public partial class AppDelegate : global::Xamarin.Forms.Platform.iOS.FormsApplicationDelegate, IUNUserNotificationCenterDelegate, IMessagingDelegate { public override bool FinishedLaunching(UIApplication app, NSDictionary options) { global::Xamarin.Forms.Forms.Init(); FirebaseApp.Configure(); RegisterForPushNotifications(); LoadApplication(new App()); return base.FinishedLaunching(app, options); } void RegisterForPushNotifications() { UNUserNotificationCenter.Current.Delegate = this; var authOptions = UNAuthorizationOptions.Alert | UNAuthorizationOptions.Badge | UNAuthorizationOptions.Sound; UNUserNotificationCenter.Current.RequestAuthorization(authOptions, (granted, error) => { if (granted) { InvokeOnMainThread(() => UIApplication.SharedApplication.RegisterForRemoteNotifications()); } }); Messaging.SharedInstance.Delegate = this; } public override void RegisteredForRemoteNotifications(UIApplication application, NSData deviceToken) { Messaging.SharedInstance.ApnsToken = deviceToken; var token = Messaging.SharedInstance.FcmToken; Preferences.Set("FCM_Token", token); } public override void FailedToRegisterForRemoteNotifications(UIApplication application, NSError error) { // 处理注册失败逻辑 } [Export("userNotificationCenter:willPresentNotification:withCompletionHandler:")] public void WillPresentNotification(UNUserNotificationCenter center, UNNotification notification, Action<UNNotificationPresentationOptions> completionHandler) { completionHandler(UNNotificationPresentationOptions.Alert | UNNotificationPresentationOptions.Sound); } [Export("messaging:didReceiveRemoteMessage:")] public void DidReceiveRemoteMessage(Messaging messaging, RemoteMessage remoteMessage) { var title = remoteMessage.AppData["title"]?.ToString(); var body = remoteMessage.AppData["body"]?.ToString(); // 自定义消息处理逻辑 } } }
- 实现共享项目的接口:
public class PushNotificationService : IPushNotificationService { public void Initialize() { // 初始化已在AppDelegate完成 } public Task<string> GetTokenAsync() { var token = Messaging.SharedInstance.FcmToken; Preferences.Set("FCM_Token", token); return Task.FromResult(token); } public void SubscribeToTopic(string topic) { Messaging.SharedInstance.SubscribeToTopic(topic); } }
测试推送
可使用Firebase控制台的Cloud Messaging模块发送测试消息,或用curl命令:
curl -X POST -H "Authorization: key=YOUR_SERVER_KEY" -H "Content-Type: application/json" -d '{ "to": "YOUR_FCM_TOKEN", "notification": { "title": "测试通知", "body": "这是一条来自FCM的测试消息" } }' https://fcm.googleapis.com/fcm/send
替换YOUR_SERVER_KEY(Firebase控制台项目设置-云消息服务中获取)和YOUR_FCM_TOKEN(应用中获取的设备token)
内容的提问来源于stack exchange,提问作者MVKozyrev
相关产品推荐
相关产品推荐

