【发布时间】:2019-01-22 22:15:59
【问题描述】:
当您通过 Firebase 控制台发送云消息时,是否可以将该消息的文本作为值和时间戳作为键存储在同一项目的实时数据库中?如果是这样,怎么做?我的最终目标是让我的应用程序中的用户可以看到通知的历史记录和发送时间。谢谢!
【问题讨论】:
标签: firebase firebase-realtime-database firebase-cloud-messaging
当您通过 Firebase 控制台发送云消息时,是否可以将该消息的文本作为值和时间戳作为键存储在同一项目的实时数据库中?如果是这样,怎么做?我的最终目标是让我的应用程序中的用户可以看到通知的历史记录和发送时间。谢谢!
【问题讨论】:
标签: firebase firebase-realtime-database firebase-cloud-messaging
感谢urgentx 为我指明了正确的方向,我在Firebase HTTP 云函数中找到了解决方案。调用它的 URL 如下所示(允许使用空格和标点符号作为通知文本):
https://[REGION]-[MY-APP-ID].cloudfunctions.net/notification?password=[PASSWORD]¬ification=[NOTIFICATION]
下面是 index.js 文件。我必须在 Android Studio 中编写代码来为每台设备订阅所有设备主题。
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
function format(number) {
if (number.toString().length < 2) {
return "0" + number;
}
return number;
}
exports.notification = functions.https.onRequest((request, response) => {
if (request.query.password == "[PASSWORD]") {
var message = {
"notification": {
"body": request.query.notification
},
"topic": "all-devices"
};
admin.messaging().send(message);
var nowUTC = new Date();
var nowEDT = new Date(nowUTC.getFullYear(), nowUTC.getMonth(), nowUTC.getDate(), nowUTC.getHours() - 4, nowUTC.getMinutes(), nowUTC.getSeconds());
var timestamp = nowEDT.getFullYear() + ":" + format(nowEDT.getMonth()) + ":" + format(nowEDT.getDate()) + ":" + format(nowEDT.getHours()) + ":" + format(nowEDT.getMinutes()) + ":" + format(nowEDT.getSeconds());
var JSONString = "{\"" + timestamp + "\":\"" + request.query.notification + "\"}";
admin.database().ref("/notifications").update(JSON.parse(JSONString));
response.send("Request to server sent to send message \"" + request.query.notification + "\" at timestamp " + timestamp + " and store in database. Await notification and check database if confirmation is needed.");
} else {
response.send("Password incorrect. Access denied.");
}
});
以下是为设备订阅所有设备主题的代码。
FirebaseMessaging.getInstance().subscribeToTopic("all-devices")
.addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
}
});
【讨论】:
您将通过自己的服务器或 Google 云功能发送通知。您可以在使用它们发送通知时存储文本。
【讨论】: