簡體   English   中英

在實時數據庫中存儲Firebase雲消息

[英]Store Firebase Cloud Message in Realtime Database

當您通過Firebase控制台發送雲消息時,是否可以將該消息的文本存儲為同一項目的實時數據庫中的值和時間戳作為密鑰? 如果是這樣,怎么辦? 我的最終目標是在我的應用程序中看到通知的歷史記錄以及向用戶發送通知的時間。 謝謝!

多虧了Emergencyx為我指明了正確的方向,所以我在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) {
                    }
                });

您將通過自己的服務器或Google雲功能發送通知。 當您使用文本發送通知時,可以存儲文本。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM