295

Hope all of you aware of this class, used to get notification token whenever firebase notification token got refreshed we get the refreshed token from this class, From following method.

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

To use this as i want to implement FCM, I extended MyClass from FirebaseInstanceIdService

But, Showing that FirebaseInstanceIdService is deprecated

Does anybody know this?, What method or class i should use instead of this to get refreshed token as this is deprecated.

I'm using : implementation 'com.google.firebase:firebase-messaging:17.1.0'

I checked the document for same there is nothing mentioned about this. : FCM SETUP DOCUMENT


UPDATE

This issue has been Fixed.

As Google deprecated the FirebaseInstanceService,

I asked the question to find the way and i get to know that We can get the Token from FirebaseMessagingService,

As before, when i asked the Question Documents were not updated but Now Google docs updated so for more info, Refer this google doc : FirebaseMessagingService

OLD From : FirebaseInstanceService (Deprecated)

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

NEW From : FirebaseMessagingService

@Override
public void onNewToken(String s) {
    super.onNewToken(s);
    Log.d("NEW_TOKEN",s);
}
8

19 Answers 19

184

Update 11-12-2020

Now FirebaseInstanceId is also deprectaed

Now we need to use FirebaseMessaging.getInstance().token

SAMPLE CODE

        FirebaseMessaging.getInstance().token.addOnCompleteListener {
            if(it.isComplete){
                firebaseToken = it.result.toString()
                Util.printLog(firebaseToken)
            }
        }

    

Yes FirebaseInstanceIdService is deprecated

FROM DOCS :- This class was deprecated. In favour of overriding onNewToken in FirebaseMessagingService. Once that has been implemented, this service can be safely removed.

No need to use FirebaseInstanceIdService service to get FCM token You can safely remove FirebaseInstanceIdService service

Now we need to @Override onNewToken get Token in FirebaseMessagingService

SAMPLE CODE

public class MyFirebaseMessagingService extends FirebaseMessagingService {

    @Override
    public void onNewToken(String s) {
        Log.e("NEW_TOKEN", s);
    }

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {

        Map<String, String> params = remoteMessage.getData();
        JSONObject object = new JSONObject(params);
        Log.e("JSON_OBJECT", object.toString());

        String NOTIFICATION_CHANNEL_ID = "Nilesh_channel";

        long pattern[] = {0, 1000, 500, 1000};

        NotificationManager mNotificationManager =
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "Your Notifications",
                    NotificationManager.IMPORTANCE_HIGH);

            notificationChannel.setDescription("");
            notificationChannel.enableLights(true);
            notificationChannel.setLightColor(Color.RED);
            notificationChannel.setVibrationPattern(pattern);
            notificationChannel.enableVibration(true);
            mNotificationManager.createNotificationChannel(notificationChannel);
        }

        // to diaplay notification in DND Mode
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = mNotificationManager.getNotificationChannel(NOTIFICATION_CHANNEL_ID);
            channel.canBypassDnd();
        }

        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID);

        notificationBuilder.setAutoCancel(true)
                .setColor(ContextCompat.getColor(this, R.color.colorAccent))
                .setContentTitle(getString(R.string.app_name))
                .setContentText(remoteMessage.getNotification().getBody())
                .setDefaults(Notification.DEFAULT_ALL)
                .setWhen(System.currentTimeMillis())
                .setSmallIcon(R.drawable.ic_launcher_background)
                .setAutoCancel(true);


        mNotificationManager.notify(1000, notificationBuilder.build());
    }
}

#EDIT

You need to register your FirebaseMessagingService in manifest file like this

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

#how to get token in your activity

.getToken(); is also deprecated if you need to get token in your activity than Use getInstanceId ()

Now we need to use getInstanceId () to generate token

getInstanceId () Returns the ID and automatically generated token for this Firebase project.

This generates an Instance ID if it does not exist yet, which starts periodically sending information to the Firebase backend.

Returns

  • Task which you can use to see the result via the InstanceIdResult which holds the ID and token.

SAMPLE CODE

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

     }
 });

##EDIT 2

Here is the working code for kotlin

class MyFirebaseMessagingService : FirebaseMessagingService() {

    override fun onNewToken(p0: String?) {

    }

    override fun onMessageReceived(remoteMessage: RemoteMessage?) {


        val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        val NOTIFICATION_CHANNEL_ID = "Nilesh_channel"

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val notificationChannel = NotificationChannel(NOTIFICATION_CHANNEL_ID, "Your Notifications", NotificationManager.IMPORTANCE_HIGH)

            notificationChannel.description = "Description"
            notificationChannel.enableLights(true)
            notificationChannel.lightColor = Color.RED
            notificationChannel.vibrationPattern = longArrayOf(0, 1000, 500, 1000)
            notificationChannel.enableVibration(true)
            notificationManager.createNotificationChannel(notificationChannel)
        }

        // to diaplay notification in DND Mode
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val channel = notificationManager.getNotificationChannel(NOTIFICATION_CHANNEL_ID)
            channel.canBypassDnd()
        }

        val notificationBuilder = NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID)

        notificationBuilder.setAutoCancel(true)
                .setColor(ContextCompat.getColor(this, R.color.colorAccent))
                .setContentTitle(getString(R.string.app_name))
                .setContentText(remoteMessage!!.getNotification()!!.getBody())
                .setDefaults(Notification.DEFAULT_ALL)
                .setWhen(System.currentTimeMillis())
                .setSmallIcon(R.drawable.ic_launcher_background)
                .setAutoCancel(true)


        notificationManager.notify(1000, notificationBuilder.build())

    }
}
6
  • 1
    Comments are not for extended discussion; this conversation has been moved to chat. Aug 22, 2018 at 5:34
  • why is nobody showing how to import FirebaseMessagingService?
    – temirbek
    Mar 20, 2020 at 14:39
  • hi, what i must use FirebaseInstallations or FirebaseMessaging ? Dec 29, 2020 at 10:38
  • @Tony currently I'm using FirebaseMessaging.getInstance()
    – AskNilesh
    Dec 30, 2020 at 7:31
  • 2
    this answer should be accepted answer to help others find the deprecated issue. many article still using FirebaseInstanceId to get new FCM token. Hopefully others read my comment
    – Yohanes AI
    Mar 18, 2021 at 7:16
151

firebaser here

Check the reference documentation for FirebaseInstanceIdService:

This class was deprecated.

In favour of overriding onNewToken in FirebaseMessagingService. Once that has been implemented, this service can be safely removed.

Weirdly enough the JavaDoc for FirebaseMessagingService doesn't mention the onNewToken method yet. It looks like not all updated documentation has been published yet. I've filed an internal issue to get the updates to the reference docs published, and to get the samples in the guide updated too.

In the meantime both the old/deprecated calls, and the new ones should work. If you're having trouble with either, post the code and I'll have a look.

5
  • 9
    The Firebase Docs have also not been updated yet. Jul 2, 2018 at 0:46
  • 1
    Yes @frank, the method do exists, but related documents not updated yet. Jul 2, 2018 at 5:27
  • @kev That sounds like a (valid) new question. Please create a new post, with a minimal complete code snippet. Jul 12, 2018 at 13:20
  • @FrankvanPuffelen already did. Have a look. stackoverflow.com/questions/51296171/…
    – kev
    Jul 12, 2018 at 13:21
  • 1
    I found about this update for Xamarin Android too. Added OnNewToken method in class that extends FirebaseMessagingService. But that method is not hit. I cannot figure out what should i do. Is it different in Android Manifest file for xamarin.
    – Prabesh
    Aug 16, 2018 at 17:03
16

Simply call this method to get the Firebase Messaging Token

public void getFirebaseMessagingToken ( ) {
        FirebaseMessaging.getInstance ().getToken ()
                .addOnCompleteListener ( task -> {
                    if (!task.isSuccessful ()) {
                        //Could not get FirebaseMessagingToken
                        return;
                    }
                    if (null != task.getResult ()) {
                        //Got FirebaseMessagingToken
                        String firebaseMessagingToken = Objects.requireNonNull ( task.getResult () );
                        //Use firebaseMessagingToken further
                    }
                } );
    }

The above code works well after adding this dependency in build.gradle file

implementation 'com.google.firebase:firebase-messaging:21.1.0'

Note: This is the code modification done for the above dependency to resolve deprecation. (Working code as of 9th May 2021)

2
  • 2
    hi, what i must use FirebaseInstallations or FirebaseMessaging ? Dec 29, 2020 at 10:39
  • 1
    Hi @Tony, For sending a cloud message through firebase, 'firebase-messaging' must be used. Looks like 'firebase-installations' is not providing the complete token which is required for sending a cloud message to other devices. Correct me if I am wrong. TIA!
    – niranj1997
    Dec 29, 2020 at 17:55
14

And this:

FirebaseInstanceId.getInstance().getInstanceId().getResult().getToken()

suppose to be solution of deprecated:

FirebaseInstanceId.getInstance().getToken()

EDIT

FirebaseInstanceId.getInstance().getInstanceId().getResult().getToken() can produce exception if the task is not yet completed, so the method witch Nilesh Rathod described (with .addOnSuccessListener) is correct way to do it.

Kotlin:

FirebaseInstanceId.getInstance().instanceId.addOnSuccessListener(this) { instanceIdResult ->
        val newToken = instanceIdResult.token
        Log.e("newToken", newToken)
    }
0
7

FirebaseinstanceIdService is deprecated. So have to use "FirebaseMessagingService"

Sea the image please:

enter image description here

public class MyFirebaseMessagingService extends FirebaseMessagingService {

    @Override
    public void onNewToken(String s) {
        super.onNewToken(s);
        Log.e("NEW_TOKEN",s);
    }

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        super.onMessageReceived(remoteMessage);
    }
}
5

Kotlin allows for even simpler code than what's shown in other answers.

To get the new token whenever it's refreshed:

class MyFirebaseMessagingService: FirebaseMessagingService() {

    override fun onNewToken(token: String?) {
        Log.d("FMS_TOKEN", token)
    }
    ...
}

To get the token from anywhere at runtime:

FirebaseInstanceId.getInstance().instanceId.addOnSuccessListener {
    Log.d("FMS_TOKEN", it.token)
}
4

In KOTLIN:- If you want to save Token into DB or shared preferences then override onNewToken in FirebaseMessagingService

override fun onNewToken(token: String) {
        super.onNewToken(token)
    }

Get token at run-time,use

FirebaseInstanceId.getInstance().instanceId
                        .addOnSuccessListener(this@SplashActivity) { instanceIdResult ->
                            val mToken = instanceIdResult.token
                            println("printing  fcm token: $mToken")
                        }
1
  • Now it's override fun onNewToken(token: String) (without the question mark).
    – Csaba Toth
    Jun 8, 2020 at 1:46
4

FCM implementation Class:

 public class MyFirebaseMessagingService extends FirebaseMessagingService {
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
Map<String, String> data = remoteMessage.getData();
if(data != null) {
 // Do something with Token
  }
}
}
// FirebaseInstanceId.getInstance().getToken();
@Override
public void onNewToken(String token) {
  super.onNewToken(token);
  if (!token.isEmpty()) {
  Log.e("NEW_TOKEN",token);
 }
}
}

And call its initialize in Activity or APP :

FirebaseInstanceId.getInstance().getInstanceId().addOnSuccessListener(
                instanceIdResult -> {
                    String newToken = instanceIdResult.getToken();
                }).addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception e) {
                        Log.i("FireBaseToken", "onFailure : " + e.toString());
                    }
                });

AndroidManifest.xml :

  <service android:name="ir.hamplus.MyFirebaseMessagingService"
        android:stopWithTask="false">
        <intent-filter>
            <action android:name="com.google.firebase.MESSAGING_EVENT" />
        </intent-filter>
    </service>

**If you added "INSTANCE_ID_EVENT" don't forget to disable it.

2

You have to use FirebaseMessagingService() instead of FirebaseInstanceIdService

2

And here the solution for C#/Xamarin.Android:

var token = await FirebaseInstallations.Instance.GetToken(forceRefresh: false).AsAsync<InstallationTokenResult>();
1

getInstance().getInstanceId() is also now deprecated and FirebaseMessaging is being used now.

FirebaseMessaging.getInstance().token.addOnCompleteListener { task ->
    if (task.isSuccessful) {
        val token = task.result
    } else {
        Timber.e(task.exception)
    }
}
3
  • What does forceRefresh do? refresh token when ever the activity is opened? Dec 7, 2020 at 15:41
  • @AbhishekAN yes it will force it to get a new tokwn. Dec 7, 2020 at 23:29
  • 1
    hi, what i must use FirebaseInstallations or FirebaseMessaging ? Dec 29, 2020 at 10:39
1

First import import com.google.firebase.messaging.FirebaseMessaging; then Simply use FirebaseMessaging.getInstance().getToken().getResult(); instead of FirebaseInstanceId.getInstance().getToken().getresult()

That's it.

1

You can use service

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

public class MyFirebaseMessagingService extends FirebaseMessagingService{
           @Override
    public void onNewToken(String s) {
        super.onNewToken(s);
        Log.e("NEW_TOKEN = = == = = =",s);
    }

}

If you want to use in Activity

FirebaseMessaging.getInstance ().getToken ().addOnCompleteListener ( task -> {
                Log.e("spalsh",task.getResult());
                    });
0

Just Add This On build.gradle. implementation 'com.google.firebase:firebase-messaging:20.2.3'

0
0

Use FirebaseMessaging instead

 FirebaseMessaging.getInstance().getToken()
    .addOnCompleteListener(new OnCompleteListener<String>() {
        @Override
        public void onComplete(@NonNull Task<String> task) {
          if (!task.isSuccessful()) {
            Log.w(TAG, "Fetching FCM registration token failed", task.getException());
            return;
          }

          // Get new FCM registration token
          String token = task.getResult();

          // Log and toast
          String msg = getString(R.string.msg_token_fmt, token);
          Log.d(TAG, msg);
          Toast.makeText(MainActivity.this, msg, Toast.LENGTH_SHORT).show();
        }
    });
0

For kotlin I use the following

val fcmtoken = FirebaseMessaging.getInstance().token.await()

and for the extension functions

public suspend fun <T> Task<T>.await(): T {
    // fast path
    if (isComplete) {
        val e = exception
        return if (e == null) {
            if (isCanceled) {
                throw CancellationException("Task $this was cancelled normally.")
            } else {
                @Suppress("UNCHECKED_CAST")
                result as T
            }
        } else {
            throw e
        }
    }

    return suspendCancellableCoroutine { cont ->
        addOnCompleteListener {
            val e = exception
            if (e == null) {
                @Suppress("UNCHECKED_CAST")
                if (isCanceled) cont.cancel() else cont.resume(result as T)
            } else {
                cont.resumeWithException(e)
            }
        }
    }
}
1
0

You can use this method in your activity , this worked for me.

private void registerInBackground() {
    FirebaseApp.initializeApp(SplashActivity.this);
    FirebaseMessaging.getInstance().getToken().addOnCompleteListener(new OnCompleteListener<String>() {
        @Override
        public void onComplete(@NonNull Task<String> task) {
            String token = task.getResult();
        }
    });
}
0

From com.google.firebase:firebase-bom:28.4.2 , the way to do it is as such:

FirebaseMessaging.getInstance().token.result

Since this is a Task, though, it doesn't return the value this way. You need to wait for it using a callback.

A nice way to solve it is via this:

@WorkerThread
fun <TResult> Task<TResult>.awaitForResult(): Task<TResult> {
    val countDownLatch = CountDownLatch(1)
    this.addOnCompleteListener {
        countDownLatch.countDown()
    }
    countDownLatch.await()
    return this
}

@WorkerThread
fun <TResult> Task<TResult>.awaitForResultOrNull(): Task<TResult>? {
    val task = awaitForResult()
    return if (task.isSuccessful)
        return task else null
}

So example usage:

val regId : String? = FirebaseMessaging.getInstance().token.awaitForResultOrNull()?.result
0

The new way

FirebaseMessaging.getInstance().getToken().addOnCompleteListener(task -> Log.e(TAG, "Token: "+task.getResult()));

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