我正在使用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 身份登录后,我看不到任何推送通知。