如何将Xamarin Forms Android应用的Azure通知中心注册升级到FCMv1
迁移Xamarin Android应用至FCMv1协议注册指南
1. 更新依赖包
确保项目引用支持FCMv1的最新版NuGet包:
- 卸载旧版Firebase相关包,安装Xamarin.Firebase.Messaging(最新稳定版)
- 安装/更新Microsoft.Azure.NotificationHubs.Android到最新稳定版
这些包原生支持FCMv1协议,无需手动处理底层协议细节。
2. 调整Firebase服务配置
- 替换为Firebase控制台下载的最新版
google-services.json,确保包含FCMv1所需的project_id、client等配置字段 - 修正
MyFirebaseMessagingService的属性配置,用SDK常量替代硬编码字符串,同时优化安全性:
注:[Service(Exported = false)] [IntentFilter(new[] { FirebaseMessagingService.IntentActionMessaging })] public class MyFirebaseMessagingService : FirebaseMessagingService { // 你的业务代码 }Exported设为false可避免外部应用调用该服务,提升安全性。
3. 优化注册代码逻辑
现有注册核心逻辑无需大幅改动,可做以下适配优化:
- 主动获取最新FCM Token,避免刷新场景下的token丢失
- 使用异步方法替代同步方法,避免阻塞主线程
调整后的代码示例:
const string TAG = "MyFirebaseMessagingService"; NotificationHub hub; public override void OnNewToken(string token) { base.OnNewToken(token); // 主动获取最新token,兼容刷新场景 var freshToken = FirebaseMessaging.Instance.GetToken().Result; SendRegistrationToServer(freshToken ?? token); } private async void SendRegistrationToServer(string token) { hub = new NotificationHub(Helpers.ApiKeys.NotificationHubName, Helpers.ApiKeys.ListenConnectionString, this); try { // 注销旧注册,避免重复条目 await hub.UnregisterAllAsync(token); } catch (Exception ex) { Log.Error(TAG, ex.Message); } var tags = new List<string>() { Entities.Settings.DeviceId }; // 新版SDK自动适配FCMv1协议完成注册 var regID = (await hub.RegisterAsync(token, tags.ToArray())).RegistrationId; Log.Debug(TAG, $"Successful registration of ID {regID}"); }
4. 配置Azure Notification Hub(关键)
客户端注册后,需确保后端Notification Hub已切换至FCMv1凭据:
- 登录Azure门户,进入目标Notification Hub
- 在「设置」>「Google (FCM)」中,选择「Firebase Cloud Messaging (V1)」选项
- 上传Firebase控制台下载的服务账号密钥JSON文件(替代旧版服务器密钥)
- 保存配置,此时Notification Hub会通过FCMv1协议推送通知
5. 验证测试
- 运行应用,查看日志确认注册成功(输出
Successful registration of ID {regID}) - 在Azure Notification Hub发送测试通知,验证设备能否正常接收
- 查看Firebase控制台「云消息传递」日志,确认通知通过FCMv1协议发送
内容的提问来源于stack exchange,提问作者Adrián Romero
相关产品推荐
相关产品推荐

