How is possible to support multi-users Android app with FCM?

Viewed 131

FCM registration generates a registration token that is associated with the device and not a particolar user. So, how to handle two common scenarios:

  • Logout: A logged in user is supposed to receieve notification, until he logs out
  • Switch user: If after logging out a new user logs in, it should have a different registration token that does't interfeer with the previous one.

This is an old documentation (from GCM)

Developers should never unregister the client app as a mechanism for logout or for switching between users, for the following reasons:

A registration token isn't associated with a particular logged in user. If the client app unregisters and then re-registers, the app can receive the same registration token or a different registration token.

Unregistration and re-registration may each take up to five minutes to propagate. During this time messages may be rejected due to the unregistered state, and messages may go to the wrong user.

Of course GCM now is deprecated, but it is likely that the same rules described here applies.

So, what are the possible ways for handling the two aforementioned scenarios? I could not find anything in the documentation.

1 Answers

I think this is a common situation. Here is one way to handle it or here is how things at my end are handled.

In the Login API, I use the following to generate a new FCM token and that is sent every time in the Login API

Firebase.messaging.token.addOnSuccessListener { fcmToken -> }

So whenever a new Sign-In or Login is performed, the fcmToken goes in its own keys and replaces the already existing one at backend.

Coming to logout situation now. When we log-out, we call this code to delete the token associated with device thus ensuring no more notifications are received when logged-out.

Firebase.messaging.deleteToken()

Further more as another level of check in the FirebaseMessagingService onMessageReceived method call, we have added a check to see if user is already logged in or not then and only anything else is performed.

Related