What to use now that FirebaseInstanceId.getInstanc

2020-01-30 04:48发布

问题:

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

回答1:

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.



回答2:

FirebaseInstanceIdService was deprecated .!

just override onNewToken() in FirebaseMessagingService

public class LatestFirebaseMessagingService extends FirebaseMessagingService {

@Override
public void onNewToken(String mToken) {
    super.onNewToken(mToken);
    Log.e("TOKEN",mToken);
}

@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
    super.onMessageReceived(remoteMessage);
}} 

InAndroidManifest.xml

<service
        android:name=".LatestFirebaseMessagingService"
        android:stopWithTask="false">
        <intent-filter>
            <action android:name="com.google.firebase.MESSAGING_EVENT" />
        </intent-filter>
</service>

getToken() This is also deprecated.!

if you need to get token in your activity use the below code.

FirebaseInstanceId.getInstance().getInstanceId().addOnSuccessListener( MyActivity.this,  new OnSuccessListener<InstanceIdResult>() {
     @Override
     public void onSuccess(InstanceIdResult instanceIdResult) {
           String mToken = instanceIdResult.getToken();
           Log.e("Token",mToken);
     }
 });