iBobb iBobb - 3 months ago 153x
Android Question

Firebase FCM token - When to send to server?

Okay so I have an app which on first start takes you through a few welcoming slides, then takes you to a login/register page and then to


I have just implemented
and the services generate a
before any of those pages have been seen by the user. How could I make it so that the service runs after I get to

The problem is I'm trying to send the token as soon as it is refreshed to the
to the appropriate user account, but since the user hasn't signed in yet, that is
and my message to the server fails. What's a good way to design this? I thought of saving the token in
and sending it to the server after the user has logged in but that creates lots of complications when the token is refreshed at some later point?!

Possible solution:

I'm not sure I completely understand how the 2 services run but say in
I just save the token into
and in MainActivity I get the value from
and then I send it to the server. In that case when the token is refreshed the new value will immediately go into
again. But I would still need to check if it's a new value in SP and then reupload it to the server. This is confusing!


Yes FCM token is generated automatically. But try to see this in a different angle.

This is how I handled it.

Let FCM generate token as soon as your app starts. OnTokenRefresh will be called and you just save it in your preferences as:

public void onTokenRefresh() {
    // Get updated InstanceID token.
    String refreshedToken = FirebaseInstanceId.getInstance().getToken();
    Log.d(TAG, "Refreshed token: " + refreshedToken);


private void sendRegistrationToServer(String token) {
    // Add custom implementation, as needed.
    SharedPreferenceUtils.getInstance(this).setValue(getString(R.string.firebase_cloud_messaging_token), token);

   // To implement: Only if user is registered, i.e. UserId is available in preference, update token on server.
   int userId = SharedPreferenceUtils.getInstance(this).getIntValue(getString(R.string.user_id), 0);
   if(userId != 0){
       // Implement code to update registration token to server

Hope you are clear with the way. Ask if you need more clearance on it.