FCM - 以不同用户身份登录后无法接收从同一设备发送的通知

FCM - cannot receive notifications sent from the same device after logging in as a different user

我正在使用 PyFCM 从我的 Flask 服务器发送通知,我正在单个 Android 设备上测试它。测试是这样的:我以用户 A 的身份登录,我对用户 B 的 post 发表评论,一旦 B 登录,它应该显示推送通知。这是我从服务器发送通知的方式:

registration_id="<device_registration_id>"
message_body = "A has commented on your post."
data_message = {"sender": current_user.id}
result =  push_service.notify_single_device(
    registration_id=registration_id,
    message_body=message_body,
    data_message=data_message
)

这就是我在 Android 的 Firebase 消息服务中接收消息的方式:

@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
    Intent intent = new Intent(this, MainActivity.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    PendingIntent resultIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT):

    String senderId = remoteMessage.getData().get("sender");
    if (senderId != currentUser.id) {
        NotificationCompat.Builder mNotificationBuilder = new NotificationCompat.Builder(this, "default_channel")
            .setSmallIcon(R.drawable.android_icon)
            .setContentTitle("New Comment")
            .setContentText(remoteMessage.getNotification().getBody())
            .setAutoCancel(true)
            .setSound(soundURI)
            .setContentIntent(resultIntent);

        NoticationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.notify(0, mNotificationBuilder.build());
    }  
}

如您所见,我有这个条件:senderId != currentUser.id 在实际撰写通知之前。这是因为我使用一台设备发送和接收通知,所以用户 A 和 B 只有一个 registation_id/token。如果我删除该条件,用户 A 将在评论 B 的 [=23] 后立即收到通知=].我想确保 B 是收到通知的人。但是,A登出,B登入后,却看不到任何推送通知。

I think onMessageReceived is only being triggered once. Say, I'm trying to send a notification from my server to all users, and I receive it while logged in as A. I clear the notification tray, log out, and log in as B, but I don't see another instance of the notification.

这是按预期工作的。根据您的 post,我假设您没有专门删除注册令牌,即同一设备的用户 重新使用 相同的令牌。所以流程现在看起来像这样:

  1. 用户A登录,所以deviceToken = A。
  2. 您从服务器向 deviceToken 发送消息。
  3. deviceToken收到消息,但是你不显示。
  4. 用户 A 注销,用户 B 登录,现在 deviceToken = B。注意:相同的 deviceToken,只是不同的用户。

在第 4 步中,您仍然期待消息到达,但从技术上讲,当用户 A 仍处于登录状态时它已经到达。onMessageReceived 不会再次触发,因为它已经收到消息预期。

为了测试您想要的行为,您需要两台设备。我实际上也在对我制作的应用程序执行此操作(使用 currentUser id 检查 senderId),所以我认为它应该也适合你。

此外,注销时 FCM 的常规和建议流程是您必须使令牌无效——有关详细信息,请参阅我的