0

I am using Firebase Messaging token for sending notifications to users from Firebase Function. But when the user decides to log out, I have to change this token for the new user. The only way that I have found to achieve this is to delete FirebaseInstanceId which I don't think is a good practice. What is the correct way to do it?

The method that I use:

    public void disableFCM(){
        FirebaseMessaging.getInstance().setAutoInitEnabled(false);
        new Thread() {
            @Override
            public void run() {
                try {
                    FirebaseInstanceId.getInstance().deleteInstanceId();
                } catch (IOException e) {
                    Toast.makeText(MainActivity.this,  e.getMessage()  , Toast.LENGTH_SHORT).show();;
                }
            }
        }.start();
    } 
Nasir
  • 57
  • 5
  • Why do you have to change the token? The token is not related to the signed in user - it's related to the device. You create the relationship yourself between the token and the user. – Doug Stevenson Jun 16 '20 at 16:21
  • Because the app continues to receive notifications until the new user logs in if I don't remove the token from the server. Should I delete the token from the server or block notifications if the user is not logged in? – Nasir Jun 16 '20 at 16:29
  • 1
    I would do both. – Doug Stevenson Jun 16 '20 at 16:33

1 Answers1

0

As Doug commented: Firebase Cloud Messaging has no information of what user a token belongs to. In fact FCM has no knowledge of users at all.

If you want to stop sending notifications to the device when the user logs out, the idiomatic way is to both delete the token from the client (as you do), and remove the association of that token with the user in your server-side mapping (database).

Also see:

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • My confusion here is that instanceId is not designed for removal every single time when the user logs out. On the other side, disassociation of user keys and token on the server side also requires the internet access. What if the user logs out when the device is offline. – Nasir Jun 16 '20 at 17:08
  • "instanceId is not designed for removal every single time when the user logs out" There's an API to remove instance ID, and no documented limit on its usage, so I'm not sure why you wouldn't call that API to meet your goals. Others have definitely done so to implement this same use-case. If you're having trouble when implementing it, edit your question to show what you tried. – Frank van Puffelen Jun 16 '20 at 20:13
  • Hi Frank. deleteInstanceId() doesn't work offline. Additionally, this approach puts you in a more confusing situation of managing the new Id generation. So in my opinion, your answer shouldn't be considered as the correct approach. I simply continued with removing the server-side mapping with Firebase Persistence. That way I may be sure that it will work offline too. – Nasir Jun 24 '20 at 15:11