Reputation: 135
When you send a cloud message via the Firebase console, is it possible to store the text of that message as a value and a timestamp as the key in the same project's realtime database? If so, how? My end goal is to have a history of notifications and the time at which they were sent visible to users in my app. Thank you!
Upvotes: 1
Views: 1969
Reputation: 135
Thanks to urgentx pointing me in the right direction, I found a solution in a Firebase HTTP Cloud Function. The URL to call it looked like this (spaces and punctuation are allowed as notification text):
https://[REGION]-[MY-APP-ID].cloudfunctions.net/notification?password=[PASSWORD]¬ification=[NOTIFICATION]
Below is the index.js file. I had to write code in Android Studio to subscribe each device to the all-devices topic.
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.");
}
});
Below is the code that subscribed the device to the all-devices topic.
FirebaseMessaging.getInstance().subscribeToTopic("all-devices")
.addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
}
});
Upvotes: 1
Reputation: 3931
You will be sending the notifications via either your own server or a Google cloud function. You can store the text when you send a notification using those.
Upvotes: 0