What to use now that FirebaseInstanceId.getInstance().getToken() is deprecated

Bhaskar Jyoti Dutta picture Bhaskar Jyoti Dutta · Jul 1, 2018 · Viewed 74k times · Source

I would like to know what would be the correct way to get Firebase token for sending push notification now that getToken() is deprecated.

Answer

Facundo Larrosa picture Facundo Larrosa · Jul 1, 2018

As documentation says :

This method was deprecated. In favour of getInstanceId().

getInstanceId() will return a Task with and InstanceIdResult. Like this:

 FirebaseInstanceId.getInstance().getInstanceId().addOnSuccessListener( new OnSuccessListener<InstanceIdResult>() {                    
                @Override
                public void onSuccess(InstanceIdResult instanceIdResult) {
                      String deviceToken = instanceIdResult.getToken();
                      // Do whatever you want with your token now
                      // i.e. store it on SharedPreferences or DB
                      // or directly send it to server 
                }
});

UPDATE:

Though is true that this approach will literally replace the use of FirebaseInstanceId.getInstanceId().getToken(), it does not solve the fact that FirebaseInstanceIdService is also deprecated leaving us with another question that is: where to use it? It can be used in any Activity context that it will always return the token. But what if we want to get the token only on creation and when it is rarely updated? For that you should override new method onNewToken from our old FirebaseMessagingService implementation: (Yes, "Messaging", not "InstanceId")

@Override
public void onNewToken(String s) {
    super.onNewToken(s);
    String deviceToken = s;
    // Do whatever you want with your token now
    // i.e. store it on SharedPreferences or DB
    // or directly send it to server 
}

This way code will remain leaner and wont even be necessary to use the first approach.