I'm sending notifications from my Flask server using PyFCM, and I'm testing it on a single Android device. The test is like this: I am signed in as user A, and I make a comment on a post of user B which should display a push notification once B signs in. Here is how I send the notification from my server:
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
)
And this is how I receive the message in the Android's Firebase messaging service:
@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());
}
}
As you can see, I have this condition: senderId != currentUser.id
before actually composing the notification. It's because I'm using one device to send and receive the notification so there's only one registation_id/token for both users A and B. If I remove that condition, user A will receive the notification right after commenting on B's post. I want to ensure that B is the one who receives the notification. However, after logging out as A and logging in as B, I couldn't see any push notification.