Showing Notifications To The Intended User Only

Viewed 57

In my Android App, there are multiple users using it and they might be logged into it in different times.

I'm using Cloud Functions to send notifications to specific tokens, which means to specific devices, but I couldn't find a way to make sure that the notification will be shown only to the user it was sent to.

Let's say that users A and B are logged in to my app on the same device. The received notification is meant to User A, but the currently logged user is User B, and I don't want User B to see User A'snotifications.

I have tried to check it this way in my FirebaseMessagingService:

String receiverEmail= remoteMessage.getData().get("sendTo");
String loggedEmail=firebaseUser.getEmail();
if (loggedEmail!=null){
   if (receiverEmail.equals(loggedEmail)){
     sendNotification(
        context.getString(R.string.your_friend_request_was_accepted),
          context.getString(R.string.by)+" "+senderName);
    }
}

and it works, only when the app is running. It doesn't work when it's closed.

I have also tried to get the logged user from the Shared Preferences and check it, but then loggedEmail was null, and it didn't work at all.

2 Answers

Since both users are using the same app installation, they're identified by the same FCM token. This means that there's no way to make the split on the server, and you'll have to direct the message to the correct user on the client.

But if neither user is current actively using the app, notification messages will be handled by the system. This means there is no concept of a currently active user, and the system will show a generic notification (that will typically activate your app when clicked).

I'd consider if FCM is really the best tool for targeting such notifications. FCM targets at its most detailed level by FCM token, while you more likely want to target by UID (or email address). I'd consider using the Firebase Realtime Database for storing messages by UID (or email address), and then use FCM for sending a notification to the device. When a user clicks the notification message, the app starts and you can retrieve the messages from the database for whoever is signed in.

If your FCM message has the notification node in its json, the system sends a notification automatically if the app is in the background, and comes to FirebaseMessagingService only if the app is in the foreground.

Since your push message already has a data node (which you're using to identify the user it's sent to), you are not required to have the notification node. Once you remove the notification node from the push message json, the flow will always come to your FirebaseMessagingService.

Related