onNewToken() is not called

22,306

Solution 1

onNewToken method is just called when the token is generated, you should retrieve the token in an activity.

Add this to your activity:

FirebaseInstanceId.getInstance().getInstanceId().addOnSuccessListener(SplashActivity.this, new OnSuccessListener<InstanceIdResult>() {
        @Override
        public void onSuccess(InstanceIdResult instanceIdResult) {
            String token = instanceIdResult.getToken();
            Log.i("FCM Token", token);
            saveToken(token);
        }
    });

Solution 2

December 2020 update : Using the new Firebase SDK (21.0.0) , you can get the token by FirebaseInstallations.getInstance() within your scope :

FirebaseInstallations.getInstance().getToken(false).addOnCompleteListener(new OnCompleteListener<InstallationTokenResult>() {
          @Override
          public void onComplete(@NonNull Task<InstallationTokenResult> task) {
              if(!task.isSuccessful()){
                  return;
              }
              // Get new Instance ID token
              String token = task.getResult().getToken();

          }
      });

Solution 3

USE this :

FirebaseMessaging.getInstance().setAutoInitEnabled(true);

Solution 4

onNewToken() will be called only when there is a new token generated or existing token updated.

You can add the following code and call wherever you want in the app to fetch the token anytime.

    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();


        }
    });

Solution 5

After connecting your app to FCM by using firebase assistant tool of android studio, use this code on your MainAcitivity class to retrieve firebase cloud messaging token : (This code works for me)

FirebaseMessaging.getInstance().token.addOnCompleteListener(OnCompleteListener { task ->
            if (!task.isSuccessful) {
                Toast.makeText(this, "${task.exception}", Toast.LENGTH_LONG).show()
                return@OnCompleteListener
            }

            // Get FCM registration token
            val token = task.result
            if (token != null) {
                Toast.makeText(this, token, Toast.LENGTH_LONG).show()
            }
        })
Share:
22,306

Related videos on Youtube

Adi Harel
Author by

Adi Harel

Updated on July 26, 2022

Comments

  • Adi Harel
    Adi Harel almost 2 years

    I was trying to get the FCM working in my app in the past few days, and I saw that the onTokenRefreshed() function and FirebaseInstanceIdService in general, is deprecated. So I followed some firebase documentations and tutorials online, but none of them seemed to be working for me. My MyFirebaseMessagingService class is:

    package com.example.android.aln4.Classes;
    
    import android.util.Log;
    import com.google.firebase.messaging.FirebaseMessagingService;
    
    public class MyFirebaseMessagingService extends FirebaseMessagingService {
    
        private static final String TAG = "MyFirebaseMessaging";
    
        @Override
        public void onNewToken(String token) {
            super.onNewToken(token);
            Log.d(TAG,"Refreshed token: "+token);
        }
    }
    

    and my manifest contains this following code:

    <service android:name=".Classes.MyFirebaseMessagingService">
        <intent-filter>
            <action android:name="com.google.firebase.MESSAGING_EVENT" />
        </intent-filter>
    </service>
    

    Plus, all of my firebae-related implemetations are up-to-date, as the following:

      //Firebase
        implementation 'com.google.firebase:firebase-crash:16.2.1'
        implementation 'com.firebase:firebase-client-android:2.5.2'
        implementation 'com.google.firebase:firebase-core:16.0.6'
        implementation 'com.google.firebase:firebase-database:16.0.6'
        implementation 'com.firebase:firebase-client-android:2.5.2'
        implementation 'com.firebaseui:firebase-ui-database:2.1.1'
        implementation 'com.google.firebase:firebase-storage:16.0.5'
        implementation 'com.google.firebase:firebase-firestore:18.0.0'
        implementation 'com.google.firebase:firebase-messaging:17.3.4'
    

    My problem in general, is that whenever I run the app, doesn't matter if it's after uninstalling and installing or on a regular run, the onNewToken() function is not called, or at least I don't see it in the Logcat. Any sort of help would be appriciated :)

    • Vladyslav Matviienko
      Vladyslav Matviienko over 5 years
      That's ok, it doesn't have to be called. If it does not - you can get the current token.
    • AskNilesh
      AskNilesh over 5 years
    • Adi Harel
      Adi Harel over 5 years
      @VladyslavMatviienko yeah, I forgot to mention, the onMessageRecieved doesn't work (or isn't called) either
    • Vladyslav Matviienko
      Vladyslav Matviienko over 5 years
      then probably you are sending the message to the wrong token. Or maybe something else. You have to check everything, nobody can do it instead of you
    • Adi Harel
      Adi Harel over 5 years
      @VladyslavMatviienko I just learnt about the whole process a few days ago, how to I do that? How do i get the right token?
    • Vladyslav Matviienko
      Vladyslav Matviienko over 5 years
      Show how you are getting the token first
    • Adi Harel
      Adi Harel over 5 years
      @VladyslavMatviienko im using the FirebaseInstanceId.getInstance().getInstanceId() method, getting the task from it, and saving it to a string like that: String token=task,getResult().getToken();
    • Vladyslav Matviienko
      Vladyslav Matviienko over 5 years
      have you checked with a debugger, or whatever if it returns you the token?
    • Adi Harel
      Adi Harel over 5 years
      @VladyslavMatviienko yes, it crashes every time it gets to that function
    • Vladyslav Matviienko
      Vladyslav Matviienko over 5 years
      that is obviously the problem.
    • Adi Harel
      Adi Harel over 5 years
      @VladyslavMatviienko nevermind, got it, its getting the token now. but the problem is that i still don't understand why i cant get the message
    • Vladyslav Matviienko
      Vladyslav Matviienko over 5 years
      are you sure that you send the message to the right token? Have you sent the right to ken to the server, etc...
    • grabarz121
      grabarz121 over 5 years
      Try to add FirebaseInstanceId.getInstance().getInstanceId().addOnComple‌​teListener in activity, and check what will be returned from that task.
    • Adi Harel
      Adi Harel over 5 years
      @VladyslavMatviienko I'm afraid you didn't understand me... But hold on to that, do I need to save the token to each user differently in the firebase database? if so, how do I send it to each one? Because from what I understand, i need to go to firebase notifications and send a notification manually....
    • Adi Harel
      Adi Harel over 5 years
      @grabarz121 Yeah I already added this and it worked, check the 7th comment here :)
    • Vladyslav Matviienko
      Vladyslav Matviienko over 5 years
      you can send them manually, or using the API. I never sent manually, therefore I have no idea how to do that, but you likely have to identify the device to send it to somehow
    • Adi Harel
      Adi Harel over 5 years
      @VladyslavMatviienko I want to do that using the API, I didn't know this opportunity is possible, if you could share a link to guide me through using this API I'd love that. Back to the topic, do I need to save the token to the user in the database every time it logs in?
    • Adi Harel
      Adi Harel over 5 years
      @VladyslavMatviienkoV are you still there...?
    • Rohit  Rathore
      Rohit Rathore almost 5 years
      @AdiHarel Did you able to resolve this issue, we are facing exact same issue and unable to find a fix for this since 2 days. Can you please let us know the solution, if your are able to resolve. Any help would be appreciated..
  • Noah
    Noah over 4 years
    The documentation says this is enabled by default.
  • Terry
    Terry over 3 years
    Thank you! So this method is now also deprecated as well. Do you happen to know what is the currently accepted method to access this now? It seems like google depricates these methods as fast as it creates them.
  • Yohanim
    Yohanim over 3 years
    onNewToken called when a new token for the default Firebase project is generated. This is invoked after app install when a token is first generated, and again if the token changes. firebase.google.com/docs/reference/android/com/google/fireba‌​se/…