tyczj
tyczj

Reputation: 73896

Update Firebase Instance ID on app update

Back in the GCM days it was recommended that every time you put out an update to your app you should check to see if a new registration id was given (since it is was not guaranteed to be the same after an update) when the app starts.

Is that still the case with FCM? I couldn't find any documentation about this

Upvotes: 5

Views: 2615

Answers (2)

JackWu
JackWu

Reputation: 1174

You do not need to check whether the token was lastest. The method onTokenRefresh() always called if a new token was generated.

What you need to do is that checking your token was sent to your server when the onTokenRefresh() was called.

Upvotes: 0

Frank van Puffelen
Frank van Puffelen

Reputation: 599391

You should check both the current token when your app runs and monitor onTokenRefresh() to detect when the token changes.

Check the current token on app/main activity startup by calling FirebaseInstanceID.getToken():

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ...
        String token = FirebaseInstanceId.getInstance().getToken();
        if (token != null) {
            sendRegistrationToServer(refreshedToken);
        }
    }
    ...

The sendRegistrationToServer() method that is called in this snippet is something you implement to send the registration token to your own server (or a serverless solution like the Firebase Database).

Monitor for changes to the token by subclassing an FirebaseInstanceIdService and overriding onTokenRefresh():

@Override
public void onTokenRefresh() {
    String refreshedToken = FirebaseInstanceId.getInstance().getToken();

    // If you want to send messages to this application instance or
    // manage this apps subscriptions on the server side, send the
    // Instance ID token to your app server.
    sendRegistrationToServer(refreshedToken);
}

See the documentation here: https://firebase.google.com/docs/cloud-messaging/android/client#sample-register

Upvotes: 3

Related Questions