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

SQL Server数据变更时如何通过FCM实现Xamarin Android跨应用推送

Xamarin.Android 基于FCM实现设备间通知推送(适配SQL Server数据变更触发场景)

前置准备

  • 已在Firebase控制台创建项目,为两款安卓应用分别完成FCM配置,下载google-services.json放到Xamarin.Android项目根目录,将文件生成操作设置为GoogleServicesJson
  • 两款应用均已完成FCM基础SDK集成,可正常获取设备专属token(即你已跑通的微软教程部分)
  • SQL Server端已配置数据变更监听能力,可通过触发器、SqlDependency等方式捕获指定表的增删操作

核心链路逻辑

整条推送流程分为4个节点:SQL Server检测到指定表增删操作 → 触发推送端应用的推送逻辑 → 推送端调用FCM接口将通知发送到Firebase服务器 → Firebase将通知转发到接收端设备并弹出提醒。


推送端C#实现代码

需要先安装Newtonsoft.JsonNuget包用于序列化请求参数:

using System.Net.Http;
using System.Text;
using Newtonsoft.Json;

// FCM推送请求实体
public class FcmPushRequest
{
    [JsonProperty("to")]
    public string RecipientDeviceToken { get; set; }
    
    [JsonProperty("notification")]
    public FcmNotificationContent Notification { get; set; }
    
    [JsonProperty("data")]
    public Dictionary<string, string> ExtraData { get; set; }
}

public class FcmNotificationContent
{
    [JsonProperty("title")]
    public string Title { get; set; }
    
    [JsonProperty("body")]
    public string Body { get; set; }
}

// 核心推送方法
public async Task<bool> SendFcmNotificationAsync(string receiverToken, string title, string content, Dictionary<string, string> extraData = null)
{
    const string fcmApiUrl = "https://fcm.googleapis.com/fcm/send";
    // 替换为Firebase控制台-项目设置-云消息传递中获取的服务器密钥
    const string fcmServerKey = "YOUR_FCM_SERVER_KEY";

    using var httpClient = new HttpClient();
    httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", $"key={fcmServerKey}");

    var pushRequest = new FcmPushRequest
    {
        RecipientDeviceToken = receiverToken,
        Notification = new FcmNotificationContent
        {
            Title = title,
            Body = content
        },
        ExtraData = extraData ?? new Dictionary<string, string>()
    };

    var jsonContent = JsonConvert.SerializeObject(pushRequest);
    var httpContent = new StringContent(jsonContent, Encoding.UTF8, "application/json");

    var response = await httpClient.PostAsync(fcmApiUrl, httpContent);
    return response.IsSuccessStatusCode;
}

生产环境不要将FCM服务器密钥硬编码到客户端安装包中,建议将推送逻辑放到自有后端服务,避免密钥泄露被恶意调用


SQL Server变更触发逻辑

可任选以下两种方案实现:

  1. 应用端监听:在推送端应用中启用SqlDependency监听目标表的增删操作,检测到变更时直接调用上面的SendFcmNotificationAsync方法推送通知,适合小范围内部使用场景
  2. 触发器+后端接口:在目标表上创建增删触发器,触发时调用自有后端的推送接口,再由后端调用FCM接口完成推送,稳定性更高,不需要推送端应用常驻后台

接收端通知处理代码

在接收端应用中继承FirebaseMessagingService处理接收逻辑:

[Service(Exported = false)]
[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 ?? "监控的表有新增/删除记录";
        // 弹出系统通知
        ShowSystemNotification(title, body);
    }

    private void ShowSystemNotification(string title, string body)
    {
        var notificationManager = GetSystemService(NotificationService) as NotificationManager;
        // 安卓8.0及以上需要先创建通知渠道
        if (Build.VERSION.SdkInt >= BuildVersionCodes.O)
        {
            var channel = new NotificationChannel("fcm_data_change", "数据变更通知", NotificationImportance.Default);
            notificationManager.CreateNotificationChannel(channel);
        }

        var notificationBuilder = new Notification.Builder(this, "fcm_data_change")
            .SetContentTitle(title)
            .SetContentText(body)
            .SetSmallIcon(Resource.Drawable.your_notification_icon) // 替换为应用内的通知图标资源
            .SetAutoCancel(true);

        notificationManager.Notify(new Random().Next(), notificationBuilder.Build());
    }

    // 监听token更新,新token需要同步到公共存储位置,避免推送失效
    public override void OnNewToken(string newToken)
    {
        base.OnNewToken(newToken);
        // 此处添加token同步逻辑,比如上传到后端数据库
    }
}

常见问题排查

  • 推送无响应:先核对接收方token是否有效、FCM服务器密钥是否和项目匹配、应用包名和Firebase控制台配置是否一致
  • 后台收不到通知:检查应用是否开启通知权限、后台运行权限,国内设备需要添加到电池优化白名单
  • 数据变更检测不生效:使用SqlDependency的场景需要确认SQL Server已开启服务代理,使用触发器的场景需要确认触发器权限配置正确

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 19:27:04