我正在使聊天应用程序尝试使用Android设备之间使用Firebase数据库,Cloud Messaging和Node.js在Android设备之间发送通知时,在应用程序处于后台时从另一个用户收到新消息时获得推送通知。

我正在关注此博客。

[https://firebase.googleblog.com/2016/08/sending-notifications-between-android.html]

下面是我尝试过的代码。

    @Override
public void onClick(View view) {
    if (view.getId() == R.id.btnSend) {
        String content = editWriteMessage.getText().toString().trim();
        if (content.length() > 0) {
            editWriteMessage.setText("");
            Message newMessage = new Message();
            newMessage.text = content;
            newMessage.idSender = StaticConfig.UID;
            newMessage.idReceiver = roomId;
            newMessage.timestamp = System.currentTimeMillis();
            FirebaseDatabase.getInstance().getReference().child("message/" + roomId).push().setValue(newMessage);
            sendNotificationToUser(newMessage.idReceiver,newMessage.text);
        }
    }
}
public  void sendNotificationToUser(String user, String message) {
    Map notification = new HashMap<>();
    notification.put("username", user);
    notification.put("message", message);
    FirebaseDatabase.getInstance().getReference().child("notificationRequests").push().setValue(notification);
}


通过使用以上代码,用户名和消息将被实时保存在notificationRequests中。

而且我真的不知道这一行代码如何接收推送通知。

    FirebaseMessaging.getInstance().subscribeToTopic("user_"+username);


而最重要的是,我需要在哪里放置上面的代码以使其工作。

并且我还创建了存储桶来托管我的node.js文件。

提前致谢。

最佳答案

编辑:我误解了你的问题。确保firebase消息传递服务在manifest.xml文件中。
原版的:
使用functions.database.ref().onCreate()方法。在ref()参数内部,将路径放置到您的通知请求中。

这是TypeScript中的一些基本代码。

export const notificationListener = functions.database
.ref('/NotificationRequests/{notification}').onCreate((snapshot, context) =>
{

try {
    admin.initializeApp();
  } catch (e) {
  }


                     //Code to send notification here



return admin.database().ref('/NotificationRequests/' + context.params.notification)
}
)


通知所需的信息位于snapshot.child('your path here')下。

See why and how this works

关于android - 当新消息发送给用户并且应用程序处于后台时,我没有收到推送通知,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55417689/

10-08 22:31
查看更多