I am building an App where I would like to generate a Push Notification for the user when a data has been changed in the Firebase Realtime Database. I would like to know if using Firebase Cloud Messaging is appropriate for it and would love some idea about how the FCM is used to send data to the App.
Asked
Active
Viewed 1,716 times
2 Answers
1
You need to use value listener to listen and send notification on data changes, example:
ValueEventListener postListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
// Send notification here
FirebaseFunctions.getInstance()
.getHttpsCallable("sendNotification")
.call(notificationData)
.continueWith(new Continuation<HttpsCallableResult, String>() {
@Override
public String then(@NonNull Task<HttpsCallableResult> task) throws Exception {
return null;
}
});
}
@Override
public void onCancelled(DatabaseError databaseError) {
// Getting Post failed, log a message
Log.w(TAG, "loadPost:onCancelled", databaseError.toException());
// ...
}
};
mPostReference.addValueEventListener(postListener);
In the function:
exports.sendNotification = functions.https.onCall((data, context) => {
// I am using FCM Topic to send notification to users.
var fcmTopic = data.fcmTopic;
console.log(data);
var payload = {
data:{
MESSAGE_TAG: "NEW_NOTIF",
MESSAGE_TITLE: "Test!",
MESSAGE_TEXT: "Test."
},
topic: fcmTopic
};
var options = {
priority: "high"
};
admin.messaging().send(payload)
.then(() => {
console.log("success");
return null;
})
.catch(error => {
console.log(error);
});
});
More info: https://firebase.google.com/docs/database/android/read-and-write#listen_for_value_events

Yash
- 3,438
- 2
- 17
- 33
-
1It's an android app :) not node-js, however the solution is the right one – J.D.1731 Aug 20 '19 at 06:28
-
1Should use database trigger instead – Aziz Aug 20 '19 at 06:31
-
How will it work for triggering the right user? Means will I have to keep a check of that too. – Samrat Aug 20 '19 at 06:35
-
Yes you have to keep track of either a registration token or topic for the user to send notification/ – Yash Aug 20 '19 at 06:36
-
I've added a sample firebase function to send notification. – Yash Aug 20 '19 at 06:41
-
bad idea to use FCM for this, use listeners, they are meant for your use case – Kushan Aug 20 '19 at 06:42
-
Listeners can be used to listen to data changes, FCM is needed to send the notification. – Yash Aug 20 '19 at 06:43
1
-
-
1Yeah well, but there are certain things you cannot do while holding a single knot. – Aziz Aug 20 '19 at 06:50
-
-
The question ```Push Notification for the user when a data has been changed in the Firebase Realtime Database``` is what the script has. So how come its the wrong knot? Perhaps you might wanna check out the repo, its actually meant for an android app. – Aziz Aug 20 '19 at 06:53
-
No offence at all. The question pretty much defined that a solution for Android is needed. – Yash Aug 20 '19 at 06:54