How to Save a FCM token in Android?

15,240

Solution 1

Just add this in your code..

    public class MyActivity extends AppCompatActivity {


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my);


        SharedPreferences prefs = getSharedPreferences("TOKEN_PREF", MODE_PRIVATE);
        String token = prefs.getString("token", "");

        Log.e("NEW_INACTIVITY_TOKEN", token);

        if (TextUtils.isEmpty(token)) {
            FirebaseInstanceId.getInstance().getInstanceId().addOnSuccessListener(MyActivity.this, new OnSuccessListener<InstanceIdResult>() {
                @Override
                public void onSuccess(InstanceIdResult instanceIdResult) {
                    String newToken = instanceIdResult.getToken();
                    Log.e("newToken", newToken);
                    SharedPreferences.Editor editor = getSharedPreferences("TOKEN_PREF", MODE_PRIVATE).edit();
                    if (token!=null){
                       editor.putString("token", newToken);
                       editor.apply();
                    }

                }
            });
        }

    }


}

Firebase Tokens are called once when the app is installed and runned for the first time so ignore the Saving the data or running this Activity/Service once the Data is Saved with Shared Prefs

Solution 2

The onTokenRefresh/onNewToken method will only be called when a new token is generated.

Quite often (especially during development) your app will already have generated an Instance ID token before you added the service. So onTokenRefresh/onNewToken will not be called, and you won't have a token in your shared preferences.

For this reason you should get the token directly from your main activity with FirebaseInstanceId.getInstance().getInstanceId() as shown in the documentation. This will pick up the token that was last generated. From there on you use onTokenRefresh/onNewToken to respond to token changes.

Solution 3

No need to Use getToken() new token already returned by onNewToken argument

@Override
public void onNewToken(String refreshedToken) {
    // No need to assign refreshedToken with getToken,
    // this method called when token refreshed then use returned refreshedToken directly,
    // use `instanceIdResult.getToken()` described below when you need to use token later throw app usage.

    // refreshedToken = FirebaseInstanceId.getInstance().getInstanceId().getResult().getToken();
    Log.d(TAG, "Refreshed token: " + refreshedToken);
    storeToken(refreshedToken);
}

getToken(); is also deprecated

Get Token in your Activity : .getToken(); is also deprecated if you need to get token in your activity then use as following:

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

     }
 });

Solution 4

May be it takes some time to generate token. If you don't get it you can generate it as follow: (Reference:https://firebase.google.com/docs/cloud-messaging/android/client?authuser=0)

 FirebaseInstanceId.getInstance().getInstanceId()
                    .addOnCompleteListener(new OnCompleteListener<InstanceIdResult>() 
 {
                        @Override
                        public void onComplete(@NonNull Task<InstanceIdResult> task) 
   {
                            if (!task.isSuccessful()) {
                                Log.w(TAG, "getInstanceId failed", 
                                task.getException());
                                return;
                            }

                            // Get new Instance ID token
                            String token = task.getResult().getToken();
                            //Here you will surely get the token so store it in 
                            //sharedpreference for future use

                        }
 });

Solution 5

Try this just uninstall and reinstall app because token is not generated everytime you play the app. It's generated when you clear sharePref or reinstall.

Share:
15,240
Don't Be negative
Author by

Don't Be negative

I am a Junior Software Developer, Interested in Mobile(Android,iOS,Windows,BlackBerry) &amp; Web development (Java/.net/php) Don't Target me For Down-votes, and Don't Beeeeee Negative,.. I will Never Down-vote... If the person is wrong I will Just Ignore them...

Updated on July 22, 2022

Comments

  • Don't Be negative
    Don't Be negative almost 2 years

    I am following this to register my deivce in Firebase

    Here I am trying to display and save the notification token

        public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService {
    
        private static final String TAG = "MyFirebaseIIDService";
    
        @Override
        public void onTokenRefresh() {
            String refreshedToken = FirebaseInstanceId.getInstance().getToken();
            Log.d(TAG, "Refreshed token: " + refreshedToken);
            storeToken(refreshedToken);
        }
    
        private void storeToken(String token) {
            //saving the token on shared preferences
            SharedPrefManager.getInstance(getApplicationContext()).saveDeviceToken(token);
        }
    }
    

    When I try to register it Always Says Token Token not generated form MainActivity

    So Here My Application is connected to Firebase.. and I know that FirebaseInstanceIdService is Deprecated I also tried with this

    public class MyFirebaseInstanceIDService extends FirebaseMessagingService {
    
        private static final String TAG = "MyFirebaseIIDService";
    
        @Override
        public void onNewToken(String refreshedToken) {
            refreshedToken = FirebaseInstanceId.getInstance().getInstanceId().getResult().getToken();
            Log.d(TAG, "Refreshed token: " + refreshedToken);
            storeToken(refreshedToken);
        }
    
        private void storeToken(String token) {
            //saving the token on shared preferences
            SharedPrefManager.getInstance(getApplicationContext()).saveDeviceToken(token);
        }
    }
    

    But Still same token is not generated

  • Don't Be negative
    Don't Be negative over 5 years
    Yes Now this is Worked fine Token Generated,,,But without Uninstall Is it not possible???
  • Don't Be negative
    Don't Be negative over 5 years
    Yes now I understand that Token only Generated only when The App is installed First time... After Getting Token I am Trying to add Shared prefs,,, But After uninstalling Its worked fine..
  • Don't Be negative
    Don't Be negative over 5 years
    So Without Uninstall Can I get Token every time When I run??? If already Token Generated I wont call the Service Which generates Token
  • Don't Be negative
    Don't Be negative over 5 years
    Yes now this works fine.. no effect on every time I open the app.. and token is saved successfully
  • Frank van Puffelen
    Frank van Puffelen over 5 years
    An uninstall indeed wipes the token. So upon a reinstall your onTokenRefresh/onNewToken gets called. As I said in my answer, if you simply want to get the token in your main activity, call FirebaseInstanceId.getInstance().getInstanceId(). If that doesn't result in a token, it hasn't been generated yet and your onTokenRefresh/onNewToken will get called eventually.
  • Don't Be negative
    Don't Be negative over 5 years
    Yup thanks,,, with your and @MLN Now I got It.. Thanks
  • Vivek Mishra
    Vivek Mishra over 5 years
    @FrankvanPuffelen can you help me with the same issue. My token is not generating even on first run. Here is the link to my question. stackoverflow.com/questions/52658578/…
  • qkx
    qkx over 3 years
    your answer is not actual anymore (they seem to change firebase lietarlly every few months, half of their docs does not work even if you copy paste it and tons of methods are deprecated or completely different).