当有新消息发送给用户并且应用程序处于后台状态时,我没有收到推送通知

时间:2019-03-29 12:43:14

标签: android node.js firebase push-notification google-cloud-platform

我正在使聊天应用程序尝试在后台使用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);
}

通过使用以上代码,用户名和消息将被实时保存在NotificationRequest中的数据库中。

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

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

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

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

提前谢谢。

1 个答案:

答案 0 :(得分:0)

编辑:我误解了您的问题。确保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