Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 535
tyczj Avatar asked Oct 18 '22 00:10

tyczj


1 Answers

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

like image 93
Frank van Puffelen Avatar answered Oct 21 '22 08:10

Frank van Puffelen