javascript - 使用 Firebase 函数向 Android 应用发送通知

标签 javascript android firebase firebase-realtime-database google-cloud-functions

我正在开发一个聊天应用程序,因此我需要发送已收到新消息的通知。 为此,我使用 Firebase Functions。 我正在使用 sendToDevice 函数,它需要 token 来发送通知。问题是,我似乎无法检索发送消息的用户的 token 。 这是我的 .js 代码:

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

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

admin.initializeApp(functions.config().firebase);


exports.sendNotification = functions.database.ref("/chats/{id}/messages/{messageId}/content")
.onWrite((change,context) => {
    var content = change.after.val();

    var payload = {
        data:{
            title: "Stranger has sent you a message",
            text: content
        }
    };

    // Here I need to the ID of the person who sent the message
    // And then compare this Id with the two Ids of the to users that are in the conversation
    // If the two Ids are different, then save the other Id as the token
    // So that I can send a notification to the other user.
    const senderId = database.ref("/chats/{id}/messages/{id}/sender/{senderId}");



    admin.messaging().sendToDevice(senderId, payload)
    .then(function(response){
        console.log("Successfully sent message: ", response);
        return null;
    })
    .catch(function(error){
        console.log("Error sending message: ", error);
    })
});

如您所见,我正在检查 messages/content 子项中是否有任何更改。 这就是我的通知内容。

然后,我尝试检索消息发件人 ID,以便知道谁发送了该消息,并检索其他用户 ID 来通知他

这可能有点令人困惑,所以这是我的 Firebase 实时数据库:

enter image description here

我做错了什么,所以这段代码可以正常工作?这是我在 android 中接收消息的 Activity :

class MyFirebaseInstanceId : FirebaseMessagingService() {
    override fun onMessageReceived(p0: RemoteMessage) {
        if(p0.data.size > 0){
            val payload :Map<String, String> = p0.data

            sendNotification(payload)

        }
    }

    private fun sendNotification(payload: Map<String, String>) {
        val builder = NotificationCompat.Builder(this)
        builder.setSmallIcon(R.drawable.common_google_signin_btn_icon_disabled)
        builder.setContentTitle(payload.get("username"))
        builder.setContentText(payload.get("email"))

        val intent = Intent(this, MainActivity::class.java)
        val stackBuilder = TaskStackBuilder.create(this)

        stackBuilder.addNextIntent(intent)

        val resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT)

        builder.setContentIntent(resultPendingIntent)

        val notificationManager =  (getSystemService(Context.NOTIFICATION_SERVICE)) as NotificationManager

        notificationManager.notify(0, builder.build())
    }
}

最佳答案

根据我们上面的评论,以下是如何使用once()val()云函数中的方法:

//.....
const refSenderId = database.ref("/chats/{id}/messages/{id}/sender/{senderId}");

return refSenderId.once('value')
 .then(dataSnapshot => { 
     const senderId = dataSnapshot.val();
     return admin.messaging().sendToDevice(senderId, payload)
 })
.then(function(response){
    console.log("Successfully sent message: ", response);
    return null;
})
.catch(function(error){
    console.log("Error sending message: ", error);
    return null;   // <- Note the return here.
})
//.....

关于javascript - 使用 Firebase 函数向 Android 应用发送通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60248867/

相关文章:

javascript - jQuery 条件代码未按预期工作 : returns 'undefined'

javascript - 如何使用实时更新数据(SignalR)

当输入是 html 内容时返回 DOM 的 Javascript 函数

android - 如何知道 MenuItem 是在 ActionBar 还是 Overflow

android - 如何更改 Android 中加载的语言以进行调试?

android - Firebase 和检索元素

javascript - React Native Arrow 语法解释

android - map 标记 fragment 按钮不起作用

node.js - 从实时数据库获取数据 firebase throw 函数

android - 存储在子集合中的 firestore 数据