Skip to content Skip to sidebar Skip to footer

Send Data To App When Data Changed In Firebase Database In Android

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 F

Solution 1:

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

Solution 2:

You need to use value listener to listen and send notification on data changes, example:

ValueEventListener postListener = newValueEventListener() {
    @OverridepublicvoidonDataChange(DataSnapshot dataSnapshot) {
        // Send notification hereFirebaseFunctions.getInstance()
                .getHttpsCallable("sendNotification")
                .call(notificationData)
                .continueWith(newContinuation<HttpsCallableResult, String>() {
                    @OverridepublicStringthen(@NonNullTask<HttpsCallableResult> task) throws Exception {
                        returnnull;
                    }
                });

    }

    @OverridepublicvoidonCancelled(DatabaseError databaseError) {
        // Getting Post failed, log a messageLog.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");
            returnnull;
        })
        .catch(error => {
            console.log(error);
        });


});

More info: https://firebase.google.com/docs/database/android/read-and-write#listen_for_value_events

Post a Comment for "Send Data To App When Data Changed In Firebase Database In Android"