基于Xamarin的Back4App推送通知完整示例求助
我太懂这种找了半天却只拿到零散碎片信息的崩溃了!之前我在做Xamarin推送集成的时候也踩过同样的坑,Parse的文档确实没把FCM的依赖关系说透——现在的Parse Server已经默认依赖FCM作为Android推送的底层服务,iOS则是通过FCM桥接APNs,所以必须先配置Firebase,再结合Parse管理推送逻辑。下面给你一套完整的、可直接复用的Xamarin.Android/iOS + FCM + Parse的推送集成方案,亲测可用:
完整的Xamarin + FCM + Parse 推送集成示例
Xamarin.Android 集成步骤
1. 前置Firebase配置
- 去Firebase控制台创建项目,添加Android应用,下载
google-services.json文件,放到Xamarin.Android项目根目录,右键设置生成操作为GoogleServicesJson。 - 在Firebase控制台的「云消息传递」页面,复制你的服务器密钥,后续配置Parse会用到。
2. 安装必要NuGet包
- 安装
Xamarin.Firebase.Messaging(FCM核心依赖) - 安装
Parse(Parse官方SDK)
3. 初始化Parse Server
在App启动入口(比如MainActivity的OnCreate方法)添加初始化代码:
protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); Xamarin.Essentials.Platform.Init(this, savedInstanceState); SetContentView(Resource.Layout.activity_main); // 初始化Parse并绑定FCM配置 ParseClient.Initialize(new ParseClient.Configuration { ApplicationId = "你的Parse App ID", Server = "你的Parse Server部署地址", PushServerUrl = "https://fcm.googleapis.com/fcm/send", PushMasterKey = "刚才复制的Firebase服务器密钥" }); }
4. 实现FCM消息接收服务
创建一个继承自FirebaseMessagingService的类,处理令牌注册和消息接收:
[Service] [IntentFilter(new[] { "com.google.firebase.MESSAGING_EVENT" })] public class AppFirebaseMessagingService : FirebaseMessagingService { // 接收并上传新的设备FCM令牌到Parse public override void OnNewToken(string token) { base.OnNewToken(token); Task.Run(async () => { ParseInstallation.CurrentInstallation.SetDeviceToken(token); await ParseInstallation.CurrentInstallation.SaveAsync(); }); } // 处理前台收到的推送消息 public override void OnMessageReceived(RemoteMessage message) { base.OnMessageReceived(message); var notification = message.GetNotification(); if (notification != null) { ShowNotification(notification.Title, notification.Body); } } // 弹出本地通知 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); // Android O及以上需要创建通知渠道 if (Build.VERSION.SdkInt >= BuildVersionCodes.O) { var channel = new NotificationChannel("push_channel", "应用推送", NotificationImportance.Default); var notificationManager = GetSystemService(NotificationService) as NotificationManager; notificationManager?.CreateNotificationChannel(channel); } var notificationBuilder = new NotificationCompat.Builder(this, "push_channel") .SetSmallIcon(Resource.Drawable.ic_notification) .SetContentTitle(title) .SetContentText(body) .SetAutoCancel(true) .SetContentIntent(pendingIntent); var notificationManagerCompat = NotificationManagerCompat.From(this); notificationManagerCompat.Notify(0, notificationBuilder.Build()); } }
5. 配置AndroidManifest权限
确保在AndroidManifest.xml中添加必要权限:
<uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.WAKE_LOCK" /> <uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
Xamarin.iOS 集成步骤
1. 前置APNs与Firebase配置
- 在Apple开发者后台创建APNs推送证书,上传到Firebase控制台的iOS应用配置页面。
- 下载
GoogleService-Info.plist文件,放到Xamarin.iOS项目根目录,右键设置生成操作为BundleResource。
2. 安装必要NuGet包
- 安装
Xamarin.Firebase.iOS.Messaging - 安装
Parse
3. 初始化Parse与FCM
在AppDelegate的FinishedLaunching方法中完成初始化:
public override bool FinishedLaunching(UIApplication app, NSDictionary options) { // 初始化Parse ParseClient.Initialize(new ParseClient.Configuration { ApplicationId = "你的Parse App ID", Server = "你的Parse Server部署地址" }); // 配置FCM Firebase.Core.App.Configure(); Firebase.Messaging.Messaging.SharedInstance.Delegate = this; // 请求用户推送权限 UNUserNotificationCenter.Current.RequestAuthorization(UNAuthorizationOptions.Alert | UNAuthorizationOptions.Badge | UNAuthorizationOptions.Sound, (granted, error) => { if (granted) { InvokeOnMainThread(() => UIApplication.SharedApplication.RegisterForRemoteNotifications()); } }); return base.FinishedLaunching(app, options); }
4. 实现FCM委托方法
让AppDelegate实现IMessagingDelegate接口,处理令牌注册和消息接收:
public class AppDelegate : UIApplicationDelegate, Firebase.Messaging.IMessagingDelegate { // 接收FCM令牌并上传到Parse public void DidReceiveRegistrationToken(Firebase.Messaging.Messaging messaging, string fcmToken) { Task.Run(async () => { ParseInstallation.CurrentInstallation.SetDeviceToken(fcmToken); await ParseInstallation.CurrentInstallation.SaveAsync(); }); } // 处理收到的推送消息 public override void DidReceiveRemoteNotification(UIApplication application, NSDictionary userInfo, Action<UIBackgroundFetchResult> completionHandler) { if (userInfo != null) { var aps = userInfo.ObjectForKey(new NSString("aps")) as NSDictionary; if (aps != null) { var alertDict = aps.ObjectForKey(new NSString("alert")) as NSDictionary; string title = alertDict?.ObjectForKey(new NSString("title")) as string; string body = alertDict?.ObjectForKey(new NSString("body")) as string; ShowLocalNotification(title, body); } } completionHandler(UIBackgroundFetchResult.NewData); } // 显示本地通知 private void ShowLocalNotification(string title, string body) { var content = new UNMutableNotificationContent(); content.Title = title; content.Body = body; content.Sound = UNNotificationSound.Default; var trigger = UNTimeIntervalNotificationTrigger.CreateTrigger(0.1, false); var request = UNNotificationRequest.FromIdentifier("push_notification", content, trigger); UNUserNotificationCenter.Current.AddNotificationRequest(request, error => { if (error != null) { Console.WriteLine($"通知创建失败: {error.LocalizedDescription}"); } }); } }
5. 配置Info.plist后台模式
在Info.plist中添加远程通知后台权限:
<key>UIBackgroundModes</key> <array> <string>remote-notification</string> </array>
测试推送
你可以直接在Parse Dashboard的「Push」页面,选择目标平台,输入标题和内容,点击发送即可——Parse会自动将请求转发给FCM/APNs,推送到你的测试设备。
内容的提问来源于stack exchange,提问作者upTheIrons
相关产品推荐
相关产品推荐

