2

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.

Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
Samrat
  • 81
  • 9

2 Answers2

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
1

Here is a script I wrote for sending notification when a change is triggered here

Aziz
  • 1,976
  • 20
  • 23
  • The question is for Android. – Yash Aug 20 '19 at 06:45
  • 1
    Yeah well, but there are certain things you cannot do while holding a single knot. – Aziz Aug 20 '19 at 06:50
  • Or the wrong knot for that matter :P – Yash Aug 20 '19 at 06:51
  • 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