Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cloud Functions for Firebase: Sending topic notification to Android device not working

I was following this tutorial from Udacity where Cloud Functions for Firebase was used to change the data of a ref on data added. I wanted to use similar function, but for sending a push notification to users subscribed to topic.

This is the function I am using.

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);

exports.sendNotification = functions.database.ref('/messages/{pushId}/text').onWrite((event) => {
    const data = event.data;
    console.log('Message received');
    if(!data.changed()){
        console.log('Nothing changed');
        return;
    }else{
        console.log(data.val());
    }

    const payLoad = {
        notification:{
            title: 'Message received',
            body: 'You received a new message',
            sound: "default"
        }
    };

    const options = {
        priority: "high",
        timeToLive: 60*60*2
    };

    return admin.messaging().sendToTopic("Message_Notifications", payLoad, options);
});

Looking at the Firebase function log I can see that the function gets called when I add a new value to the database. The I am subscribing to the topic in the mainactivity with

FirebaseMessaging.getInstance().subscribeToTopic("Message_Notification");

And after a few hours now I can see the topic in my topics list in firebase notification console. I send a notification from there and it worked.

What are the other things I need to do to have a notification show up every time a new message is added?

Any suggestion is appreciated. I am fairly new to Firebase. So if there is a better blog/post about it please redirect me so that I can learn more.

Thanks in advance.

like image 356
raymanM Avatar asked Mar 20 '17 00:03

raymanM


People also ask

How do we can send notifications to a specific device through firebase cloud messaging service?

For sending FCM notification payload you can use Firebase Cloud Messaging Tool in firebase console. And click on Send your first message. Then enter the Title and body field. If you wish to send it to a particular device then click on Send test message and enter the FCM registration token.


1 Answers

In your Android app, you are subscribing to "Message_Notification" topic.

In your script, you're sending to "Message_Notifications" topic.

Either add an s in your Android app for the name of the topic or remove the excess s from your script.

like image 153
AL. Avatar answered Oct 19 '22 01:10

AL.