简体   繁体   中英

Unable to send push notification to android device using firebase cloud messaging

I am trying to send a notification to an android device using firebase cloud messaging.

Below is sendNotification which is a cloud function I have deployed on firebase:

const sendNotification = (owner_uid: any, type: any) => {
    return new Promise((resolve, reject) => {
        admin.firestore().collection('users').doc(owner_uid).get().then((doc) => {
            if (doc.exists && doc.data()?.token) {
                if (type === 'new_comment') {

                    console.log('NEW COMMENT');
                    console.log('TOKEN: ' + doc.data()?.token);

                    admin.messaging().sendToDevice(doc.data()?.token, {
                        data: {
                            title: 'A new comment has been made on your post',
                        }
                    }).then((sent) => {
                        console.log("SENT COUNT " + sent.successCount);
                        console.log('SENT APPARENTLY')
                        resolve(sent);
                    });
                }
            }
        });
    });
}

And here is where I'm calling this function:

export const updateCommentsCount = functions.firestore.document('comments/{commentId}').onCreate(async (event) => {
    const data = event.data();

    const postId = data?.post;

    const doc = await admin.firestore().collection('posts').doc(postId).get();

    if (doc.exists) {
        let commentsCount = doc.data()?.commentsCount || 0;

        commentsCount++;

        await admin.firestore().collection('posts').doc(postId).update({
            'commentsCount': commentsCount
        })

        return sendNotification(doc.data()?.owner, 'new_comment');
    } else {
        return false;
    }
})

However, I'm not receiving a notification on the android device.

And here are the cloud function logs when I leave a comment:

火灾日志

Can someone please tell me why is happening, & how it can be resolved? I can show further code if required.

I managed to find the solution.

In the notification sending method, sendToDevice , I updated the key "data", to "notification" and the notification is now being automatically sent & displayed on the original user's device.

Here is the updated

admin.messaging().sendToDevice(doc.data()?.token, {
    notification: {
        title: 'A new comment has been made on your post',
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM