android - 将 FCM 从 Firestore 发送到 Android 应用程序需要什么?
问题描述
这是我到目前为止所拥有的:
- 在 Android 上,用户登录并更改 Firestore 文档。
- Firestore 文档已更新
- 云功能被触发
- 云功能使用设备令牌向设备发送消息
- 在 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)`
解决方案
如果你想向设备发送消息,你需要编写代码来收集你的应用程序中的设备令牌,并将它们存储或发送到你的后端。这一切都不会自动发生。
推荐阅读
- python - 根据这些行中的值创建包含现有列的行的新列
- java - 如何使用 RestAssured post 方法上传多个图像
- android - Android:AppCompatAcitivity 的构造函数在哪里?
- kubernetes - 在 Kubernetes 集群上应用 Calico 网络时出错
- java - Android 应用程序读写物理内存
- spring-boot - Spring Boot - 外部化数据库设置
- vba - 在 MS Word 中使用 VBA 更改所选表单域的颜色
- python - 如何用一个 CSV 列规范化 Python 矩阵?
- python - 为什么对象没有属性'tbody'?
- javascript - 如何使用反应路由器