在实时数据库中存储Firebase云消息

时间:2018-08-16 02:27:54

标签: firebase firebase-realtime-database firebase-cloud-messaging

当您通过Firebase控制台发送云消息时,是否可以将该消息的文本存储为同一项目的实时数据库中的值和时间戳作为密钥?如果是这样,怎么办?我的最终目标是在我的应用程序中看到通知的历史记录以及向用户发送通知的时间。谢谢!

2 个答案:

答案 0 :(得分:1)

由于迫切需要向正确的方向发展,所以我在Firebase HTTP Cloud Function中找到了解决方案。调用它的URL如下所示(允许将空格和标点符号用作通知文本):

https://[REGION]-[MY-APP-ID].cloudfunctions.net/notification?password=[PASSWORD]&notification=[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) {
                    }
                });

答案 1 :(得分:0)

您将通过自己的服务器或Google云功能发送通知。当您使用文本发送通知时,可以存储文本。