1

我正在使用PyFCM从我的 Flask 服务器发送通知,并且正在单个 Android 设备上对其进行测试。测试是这样的:我以用户 A 的身份登录,我对用户 B 的帖子发表评论,一旦 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 只有一个注册 ID/令牌。如果我删除该条件,用户 A 将在评论 B 的帖子后立即收到通知。我想确保 B 是收到通知的人。但是,在以 A 身份注销并以 B 身份登录后,我看不到任何推送通知。

4

1 回答 1

1

我认为 onMessageReceived 只会被触发一次。说,我试图从我的服务器向所有用户发送通知,我在以 A 身份登录时收到它。我清除通知托盘,注销并以 B 身份登录,但我没有看到另一个实例的通知。

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

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

在第 4 步中,您仍然希望收到一条消息,但从技术上讲,它在用户 A 仍然登录时已经到达。onMessageReceived不会再次触发,因为它已经按预期收到了消息。

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

此外,退出时使用 FCM 的通常和建议流程是您必须使令牌无效 - 有关更多详细信息,请参阅我的答案

于 2018-04-27T06:33:07.113 回答