Firebase消息传递 - 无法接收来自订阅的通知

时间:2017-11-14 10:28:38

标签: android firebase firebase-cloud-messaging

情况如下:我有一个firebase云功能,每次写入某个数据库集合(称为“jamrooms”)时都会运行。 NodeJS脚本如下:

const functions = require('firebase-functions');

// The Firebase Admin SDK to access the Firebase Realtime Database.
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);

exports.newJamroom = functions.database.ref('/jamrooms/{jamroomId}').onWrite(event => {

        // Grab the current value of what was written to the Realtime Database.
        var jamroomId = event.params.jamroomId;

        var topic = "new-jamroom";
        var payload = {
            data: {
                title: "New jamroom available !",
                body: String("Jamroom id = ").concat(jamroomId)
            }
        };

        // Send a message to devices subscribed to the provided topic.
        return admin.messaging().sendToTopic(topic, payload)
            .then(function (response) {
                // See the MessagingTopicResponse reference documentation for the
                // contents of response.
                console.log("Successfully sent message:", response);
            })
            .catch(function (error) {
                console.log("Error sending message:", error);
            });
});

在客户端(Android),我订阅了“new-jamroom”主题:

FirebaseMessaging.getInstance().subscribeToTopic("new-jamroom");

每次将新的键值对添加到集合中时,脚本都会成功执行:

enter image description here

但客户端从未在后台或前台收到通知。

我不知道在哪里可以了解什么是不对的。

更新

即使从控制台发送通知(使用控制台中存在的“new-jamroom”主题)也不会将其发送到客户端(已发送Firebase记录0)。

1 个答案:

答案 0 :(得分:1)

由于您的有效负载包含data密钥,因此您只发送数据消息,而不是通知:

    var payload = {
        data: {
            title: "New jamroom available !",
            body: String("Jamroom id = ").concat(jamroomId)
        }

接收方的数据消息和通知消息为handled differently。仅数据消息导致在接收器中调用onMessageReceived()。要生成通知,请使用notification密钥构建有效负载:

    var payload = {
        notification: {  // <= CHANGED
            title: "New jamroom available !",
            body: String("Jamroom id = ").concat(jamroomId)
        }