FCM Token (google) associate with the user, at what time?

An app that has User Registration and Login, consequently an ID for each user.

When is the FCM Token generated ?

I implementing inside: onTokenRefresh (), the Token can be generated before I have a user with ID for me to associate...

I ask this, because if it is generated before the user signs up, how do I associate the Token with the user ?

Author: Sergio, 2016-09-20

1 answers

Official documentation translated: documentation

On the first launch of the application, the FCM SDK generates a registration token of the client application instance. To target the application to single devices or create groups of devices, you will need to access this token.

Obs.: With each authentication, a new token is generated for the user. For this reason I write the token in SharedPreferences because it is only possible to have access to this token during the authentication. As a suggestion, follow below how I did to write the current token to SharedPreferences:

Add Service in manifest :

    <service
        android:name=".Messaging.FirebaseIDService">
        <intent-filter>
            <action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
        </intent-filter>
    </service>

Class .Messaging.FirebaseIDService with writing the token to sharedPreferences :

public class FirebaseIDService extends FirebaseInstanceIdService {
    private static final String TAG = "FirebaseIDService";

    @Override
    public void onTokenRefresh() {
        String refreshedToken = FirebaseInstanceId.getInstance().getToken();
        Log.d(TAG, "Refreshed token: " + refreshedToken);
        sendRegistrationToServer(refreshedToken);
    }

    private void sendRegistrationToServer(String token) {
        SharedPreferences SP = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
        SharedPreferences.Editor editor = SP.edit();
        editor.putString("CfgTokenFCM", token);
        editor.apply();
    }
}

Ready. Now you can read the token in any class and when you want with:

        // Read CfgTokenFCM
        SharedPreferences SP = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
        cfgTokenFCM = SP.getString("CfgTokenFCM", "");

I particularly still write to firebase Realtime database on a node user-specific, with UserID, UserName, UserEmail, PhotoURL and etc.

 0
Author: Itapox, 2017-06-08 02:05:52