首页 > 解决方案 > 将 FCM 从 Firestore 发送到 Android 应用程序需要什么?

问题描述

这是我到目前为止所拥有的:

  1. 在 Android 上,用户登录并更改 Firestore 文档。
  2. Firestore 文档已更新
  3. 云功能被触发
  4. 云功能使用设备令牌向设备发送消息
  5. 在 Android 上,FirebaseMessagingService 应该会收到消息,但不会。

我怀疑我缺少的部分是设备令牌注册。由于我的服务器是 Firebase 并且我的用户通过 Firebase 登录,我是否需要采取额外的步骤将设备令牌发送到 Firebase 以便我的云功能可以访问它?换句话说,我是自己将它们存储在 Firestore 中,还是作为 Firebase 控制的某些“用户”集合的一部分成为标准?有关更多上下文,我从网上找到的示例中调整了我的云功能:

云功能:

exports.coolThingIsHappening = functions.firestore.document("coolstuf/{userId}")
    .onWrite(async (change, context) => {
        console.log("coolThingIsHappening is triggered");
        const userId = context.params.userId;
        const after = change.after.data();
        const payload = {
            data: after
        }
        const tokensSnapshot = await admin.database()
            .ref(`/users/${userId}/notificationTokens`).once('value');
        if (!tokensSnapshot.hasChildren()) {
            const logMsg = `user ${userId} has no notification tokens.`
            console.log(logMsg)
            return logMsg;
        }
        console.log("FCM tokens found")
        const tokens = Object.keys(tokensSnapshot.val());
        const response = await admin.messaging().sendToDevice(tokens, payload);
        const tokensToRemove: Promise<void>[] = [];
        console.log(`response results: ${response.results.length}`)
        response.results.forEach((result, index) => {
            console.log(`fcm sent: ${result.messageId}`)
            const error = result.error;
            if (error!.code === 'messaging/invalid-registration-token' ||
                error!.code === 'messaging/registration-token-not-registered') {
                tokensToRemove.push(tokensSnapshot.ref.child(tokens[index]).remove());
            }
        });
        return Promise.all(tokensToRemove);
    });

编辑

我已着手将 fcm 令牌保存到 Firestore。知道如何将上面的代码从database-centric 转换为firestore-centric。我遇到了一些麻烦。安卓代码:

val data = mapOf("token" to it)
val collectionName = "users/${uid}/deviceTokens/"
   FirebaseFirestore.getInstance().collection(collectionName).document()
  .set(data)`

标签: androidfirebasegoogle-cloud-firestorefirebase-cloud-messaging

解决方案


如果你想向设备发送消息,你需要编写代码来收集你的应用程序中的设备令牌,并将它们存储或发送到你的后端。这一切都不会自动发生。


推荐阅读