33

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 :)

19
  • 4
    That's ok, it doesn't have to be called. If it does not - you can get the current token. Feb 1, 2019 at 8:15
  • Read this stackoverflow.com/a/51835126/7666442
    – AskNilesh
    Feb 1, 2019 at 8:21
  • @VladyslavMatviienko yeah, I forgot to mention, the onMessageRecieved doesn't work (or isn't called) either
    – Adi Harel
    Feb 1, 2019 at 8:22
  • 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 Feb 1, 2019 at 8:23
  • 1
    @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.. Sep 20, 2019 at 11:30

7 Answers 7

26

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);
        }
    });
2
  • 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.
    – Terry
    Jan 29, 2021 at 23:00
  • 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/firebase/…
    – Yohanim
    Mar 24, 2021 at 8:43
13

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

          }
      });

EDIT : December 2022 update : Using new Firebase SDK (23.1.0) :

   FirebaseMessaging.getInstance().getToken().addOnCompleteListener(new OnCompleteListener<String>() {
          @Override
          public void onComplete(@NonNull Task<String> task) {
              if(!task.isSuccessful()){
                  return;
              }
              // Get new Instance ID token
              String token = task.getResult();
             
          }
      });
1
  • So why do most of the examples just have getInstanceId() then add a listener there - this is not a method in my version of the SDK perhaps? The other examples that do getToken().addOnCompleteListener, appear to be there.. But the other examples are listed with confidence? Mobile development is starting to look like "google your brains out until you have an app". For example, I couldn't find anything that mentioned getNotification for days, then I saw it while hovering in the tooltip or it still wouldn't work. Any secrets?
    – Dan Chase
    Jun 27 at 15:04
4

USE this :

FirebaseMessaging.getInstance().setAutoInitEnabled(true);
1
  • 8
    The documentation says this is enabled by default.
    – Noah
    Oct 3, 2019 at 23:26
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();


        }
    });
4

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()
            }
        })
1

Receive a token like this (Kotlin):

FirebaseMessaging.getInstance().token.result?.let{ Log.e(TAG, "onCreate: $it")}
-1

You only need onNewToken() to signal your app that it needs to send the token again.

You could do this at some entry point of your app:

private void doPushCheck() throws ExecutionException, InterruptedException {
    if (isPushTokenAlreadySent()) {
        return;
    }
    Task<InstanceIdResult> instanceId = FirebaseInstanceId.getInstance().getInstanceId();
    Tasks.await(instanceId);
    InstanceIdResult result = instanceId.getResult();
    if (result != null) {
        String sPushToken = result.getToken();
        if (!TextUtils.isEmpty(sPushToken)) {
            [send token to your backend and verify your server response]
            setPushTokenSent(true);
        }
    }
}

On your on onNewToken() method override, you could simply do this:

@Override
public void onNewToken(@NonNull String sPushToken) {
    setPushTokenSent(false);
}

Methods isPushTokenAlreadySent() and setPushTokenSent() could be your favourite way of persisting data, for example with SharedPreferences:

private boolean isPushTokenAlreadySent() {
    SharedPreferences preferences = getApplicationContext().getSharedPreferences("push_token", Context.MODE_PRIVATE);
    return preferences.getBoolean("registered", false);
}

private void setPushTokenSent(boolean bSent) {
    SharedPreferences preferences = getApplicationContext().getSharedPreferences("push_token", Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = preferences.edit();
    preferences.getBoolean("registered", bSent);
    editor.apply();
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.