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

如何在Firebase实时数据库新增数据时向Android App推送通知?

实现实时数据库新增数据时向Android App发送通知

整体思路

通过Firebase Cloud Functions监听实时数据库的新增节点事件,触发后调用Firebase Cloud Messaging(FCM)向Android设备推送通知。核心步骤包括:Android端获取并存储FCM令牌、编写云函数触发器、部署云函数。

步骤1:Android端准备FCM令牌

  1. 确保Android项目已集成Firebase Messaging
  2. 自定义MyFirebaseMessagingService类,获取设备令牌并上传到实时数据库:
class MyFirebaseMessagingService : FirebaseMessagingService() {
    override fun onNewToken(token: String) {
        super.onNewToken(token)
        // 将令牌上传到实时数据库的fcmTokens节点,可关联用户ID存储
        FirebaseDatabase.getInstance().getReference("fcmTokens")
            .push()
            .setValue(token)
    }

    override fun onMessageReceived(remoteMessage: RemoteMessage) {
        super.onMessageReceived(remoteMessage)
        // 处理收到的通知,弹出系统通知
        val title = remoteMessage.notification?.title ?: "新通知"
        val body = remoteMessage.notification?.body ?: "有新记录添加"
        // 此处实现通知弹出逻辑,使用NotificationManager完成
    }
}
  1. 在AndroidManifest.xml中注册该服务:
<service
    android:name=".MyFirebaseMessagingService"
    android:exported="false">
    <intent-filter>
        <action android:name="com.google.firebase.MESSAGING_EVENT" />
    </intent-filter>
</service>

步骤2:编写Firebase Cloud Function

  1. 用Firebase CLI初始化云函数项目(本地安装CLI后执行firebase init functions)
  2. 在functions/index.js中编写触发器代码:
const functions = require("firebase-functions");
const admin = require("firebase-admin");
admin.initializeApp();

// 监听db/0节点下的新增数据
exports.sendNewDataNotification = functions.database.ref('/db/0/{pushId}')
    .onCreate(async (snapshot, context) => {
        // 获取新增的记录数据
        const newRecord = snapshot.val();
        const notifyTitle = "新记录已添加";
        const notifyContent = `姓名:${newRecord.name},年龄:${newRecord.age}`;

        // 读取数据库中存储的FCM令牌
        const tokensSnap = await admin.database().ref('/fcmTokens').once('value');
        const tokens = Object.keys(tokensSnap.val() || {});

        if (tokens.length === 0) {
            functions.logger.info("无可用的FCM设备令牌");
            return;
        }

        // 构建FCM通知 payload
        const payload = {
            notification: {
                title: notifyTitle,
                body: notifyContent,
                clickAction: "NOTIFICATION_CLICK" // 对应Android端处理点击的action
            },
            data: {
                recordId: context.params.pushId, // 传递新增记录的ID,方便后续跳转
                name: newRecord.name
            }
        };

        // 发送通知并清理无效令牌
        try {
            const response = await admin.messaging().sendToDevice(tokens, payload);
            const invalidTokens = [];

            response.results.forEach((result, idx) => {
                const err = result.error;
                if (err) {
                    functions.logger.error(`推送失败至令牌 ${tokens[idx]}:`, err);
                    // 标记无效令牌待删除
                    if (err.code === 'messaging/invalid-registration-token' ||
                        err.code === 'messaging/registration-token-not-registered') {
                        invalidTokens.push(tokensSnap.ref.child(tokens[idx]).remove());
                    }
                }
            });

            return Promise.all(invalidTokens);
        } catch (err) {
            functions.logger.error("推送通知出错:", err);
        }
    });

步骤3:部署云函数

在终端执行命令:

firebase deploy --only functions

注意事项

  • 数据库规则:确保云函数有权限读取fcmTokens节点,可在Firebase控制台的实时数据库规则中配置:
{
  "rules": {
    "fcmTokens": {
      ".read": "true",
      ".write": "auth != null"
    },
    "db": {
      ".read": "true",
      ".write": "auth != null"
    }
  }
}
  • 针对特定用户推送:如果不需要给所有设备发通知,可在存储FCM令牌时关联用户ID,新增数据时携带目标用户ID,云函数只读取对应用户的令牌发送。
  • 原web端的push代码无需修改,只要数据写入db/0/节点,就会触发云函数发送通知。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 16:45:35