69

In the new Firebase, under Notification, they have mentioned that developer can send notification to a particular device. For that, in console it asks for an FCM token. What is it exactly and how can I get that token?

AL.
  • 33,241
  • 9
  • 119
  • 257
arunrk
  • 863
  • 1
  • 6
  • 9

5 Answers5

73

What is it exactly?

An FCM Token, or much commonly known as a registrationToken like in . As described in the GCM FCM docs:

An ID issued by the GCM connection servers to the client app that allows it to receive messages. Note that registration tokens must be kept secret.


How can I get that token?

Update: The token can still be retrieved by calling getToken(), however, as per FCM's latest version, the FirebaseInstanceIdService.onTokenRefresh() has been replaced with FirebaseMessagingService.onNewToken() -- which in my experience functions the same way as onTokenRefresh() did.


Old answer:

As per the FCM docs:

On initial startup of your app, the FCM SDK generates a registration token for the client app instance. If you want to target single devices or create device groups, you'll need to access this token.

You can access the token's value by extending FirebaseInstanceIdService. Make sure you have added the service to your manifest, then call getToken in the context of onTokenRefresh, and log the value as shown:

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

    // TODO: Implement this method to send any registration to your app's servers.
    sendRegistrationToServer(refreshedToken);
}

The onTokenRefreshcallback fires whenever a new token is generated, so calling getToken in its context ensures that you are accessing a current, available registration token. FirebaseInstanceID.getToken() returns null if the token has not yet been generated.

After you've obtained the token, you can send it to your app server and store it using your preferred method. See the Instance ID API reference for full detail on the API.

AL.
  • 33,241
  • 9
  • 119
  • 257
  • 1
    When that FCM token get generate for the first time? Does firebase authentication is need like firebase storage? – arunrk Jun 07 '16 at 06:25
  • The `registrationToken` usually gets generated for the first time whenever the app is first installed. And when following the usual process. You have to send the generated `registrationToken` to your app server. Sorry, but can you elaborate on *Does firebase authentication is need like firebase storage* ? – AL. Jun 07 '16 at 06:36
  • 1
    @arunrk - i recommend you to go through this : https://github.com/firebase/quickstart-android/tree/master/messaging – AnhSirk Dasarp Jun 07 '16 at 06:42
  • 1
    @AL we'll soon revert to calling that value a server key, since calling it a token just introduces more confusion. The OP here was clearly asking about a client-device token, so I wouldn't talk about the server key/token here. – Frank van Puffelen Nov 25 '16 at 04:57
  • @FrankvanPuffelen I see. Noted Puf. I'll go ahead and rollback the edit on my answer. Thanks! :) – AL. Nov 25 '16 at 06:30
  • I have a question, is the registrationToken for Cloud Messaging and the Instance ID as refered here are same thing? Can it be used for topic subscripton on server side? https://developers.google.com/instance-id/reference/server#create_relationship_maps_for_app_instances – Naveed Ahmed Dec 14 '16 at 13:35
  • @NaveedAhmed - Nope. See this [answer](http://stackoverflow.com/a/33504570/4625829) by Arthur Thompson. – AL. Dec 15 '16 at 03:03
  • device id and registration token both are same in fcm ? because my api developer requires DeviceToken and RegisterationToken – Adeel Turk Mar 22 '17 at 06:10
  • @AdeelTurk It depends on where you're using it. Some APIs refer to the `deviceId` as the actual unique Id of an Android device. RegistrationToken is most often the same as the Registration Token for FCM – AL. Mar 22 '17 at 08:01
  • 1
    @Al Thanks alot .. actually in ios u need both Device token and registration token to make a successfull push notification call from server side. So we tested it with only the token recived in onTokenRefreshed() and tinggg!! it worked – Adeel Turk Mar 22 '17 at 10:06
  • "If you want to target single devices or create device groups, you'll need to access this token." And yet, I've yet to see any example of using the token when making a push notification. – AlxVallejo Jul 05 '17 at 02:31
  • @AlxVallejo There should be plenty here in Stack Overflow and by simply Googling FCM downstream messaging. You could also check out the Stack Overflow documentation I made [here](https://stackoverflow.com/documentation/firebase-cloud-messaging/8242/firebase-cloud-messaging#t=201707050318389784278) -- it uses cURL/Postman for sending a message. You could simply just change the payload to target the token you have. – AL. Jul 05 '17 at 03:20
  • @AL. it looks like you're just setting the token as an Authorization header. Is that correct? If so that is the short answer, but I can't find an example of using that in my case (non-http call) via react native and firebase' cloud functions. I feel like things happen under the hood once my SDK is set up, but i'm not positive – AlxVallejo Jul 05 '17 at 14:46
  • @AlxVallejo Hi. Sorry, but I'm unable to picture what seems to be wrong. Do you have an actual post with all the details in it? However to answer your question, I'm not putting the token in the header, it's in the payload (body). The important value that should be in the header is the Server Key (for Authorization). – AL. Jul 05 '17 at 16:23
  • Ok, I think i got it. I think the question in my head is ... should you pass the token to every request read by the firebase cloud function, or do you check for the user's token from the function itself ... i might open a new question if i can't figure that out. – AlxVallejo Jul 05 '17 at 16:25
  • how do you send the token to your app server? – mcmillab Aug 26 '17 at 21:18
  • @mcmillab In my case, I'm using Firrbase DB. So I just save it to a specific node. – AL. Aug 27 '17 at 01:45
  • @AL. i've used the `server key` `web api key` but in case of server key it tell me `invalid token` and in case of `web api key` it tells me `unauthorized`. Can you please guide me what is it that I'm doing wrong – Gardezi Oct 02 '17 at 16:30
  • @FrankvanPuffelen ^^ can you please guide me Thanks – Gardezi Oct 02 '17 at 16:30
  • @Gardezi Hi. Invalid token is different from 401. It's usually thrown when the token you're sending the message to is not properly formatted. Maybe look into [this post](https://stackoverflow.com/a/42360186/4625829) – AL. Oct 03 '17 at 02:24
  • @AL. sure I'll post another question – Gardezi Oct 03 '17 at 03:37
  • @AL. Here is the link to my question https://stackoverflow.com/questions/46537058/getting-invalid-token-in-firebase-cloud-messaging-in-curl-command-and-postman – Gardezi Oct 03 '17 at 04:06
  • I've just done the above, but it generates the same tokens for different users. How can i get a unique token for each user? (PS I'm using one device for testing different accounts). Could that have something to do with it? – Pamela Sillah Mar 09 '18 at 17:10
  • @PamelaSillah Using a single device could actually cause that. Are you [handling the logout](https://stackoverflow.com/a/43197589/4625829) of the user properly? – AL. Mar 09 '18 at 17:13
  • Thanks @AL, i actually wasn't handling the logout the proper way – Pamela Sillah Mar 09 '18 at 20:04
  • does uninstalling the application or resetting the device change the token? – user1166085 Mar 12 '18 at 03:49
  • @user1166085 Yes. See my [answer here](https://stackoverflow.com/a/41338632/4625829) – AL. Mar 12 '18 at 06:02
  • This method doesn't work anymore. "`onRefreshToken()`" doesn't exist anymore. You should now use `@Override public void onNewToken(String token) {`. – payne Aug 16 '18 at 22:38
  • Broken link for GCM – Suragch Jun 07 '19 at 23:23
6

Here is simple steps add this gradle:

dependencies {
  compile "com.google.firebase:firebase-messaging:9.0.0"
}

No extra permission are needed in manifest like GCM. No receiver is needed to manifest like GCM. With FCM, com.google.android.gms.gcm.GcmReceiver is added automatically.

Migrate your listener service

A service extending InstanceIDListenerService is now required only if you want to access the FCM token.

This is needed if you want to

  • Manage device tokens to send a messages to single device directly, or Send messages to device group, or
  • Send messages to device group, or
  • Subscribe devices to topics with the server subscription management API.

Add Service in manifest

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

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

Change MyInstanceIDListenerService to extend FirebaseInstanceIdService, and update code to listen for token updates and get the token whenever a new token is generated.

public class MyInstanceIDListenerService extends FirebaseInstanceIdService {

  ...

  /**
   * Called if InstanceID token is updated. This may occur if the security of
   * the previous token had been compromised. Note that this is also called
   * when the InstanceID token is initially generated, so this is where
   * you retrieve the token.
   */
  // [START refresh_token]
  @Override
  public void onTokenRefresh() {
      // Get updated InstanceID token.
      String refreshedToken = FirebaseInstanceId.getInstance().getToken();
      Log.d(TAG, "Refreshed token: " + refreshedToken);
      // TODO: Implement this method to send any registration to your app's servers.
      sendRegistrationToServer(refreshedToken);
  }

}

For more information visit

  1. How to import former GCM Projects into Firebase
  2. How to force a token refresh
  3. How to access the token
  4. How to set up firebase
Community
  • 1
  • 1
Md. Sajedul Karim
  • 6,263
  • 3
  • 47
  • 77
5

They deprecated getToken() method in the below release notes. Instead, we have to use getInstanceId.

https://firebase.google.com/docs/reference/android/com/google/firebase/iid/FirebaseInstanceId

Task<InstanceIdResult> task = FirebaseInstanceId.getInstance().getInstanceId();
task.addOnSuccessListener(new OnSuccessListener<InstanceIdResult>() {
      @Override
      public void onSuccess(InstanceIdResult authResult) {
          // Task completed successfully
          // ...
          String fcmToken = authResult.getToken();
      }
});

task.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
    // Task failed with an exception
    // ...
}
});

To handle success and failure in the same listener, attach an OnCompleteListener:

task.addOnCompleteListener(new OnCompleteListener<InstanceIdResult>() {
@Override
public void onComplete(@NonNull Task<InstanceIdResult> task) {
    if (task.isSuccessful()) {
        // Task completed successfully
        InstanceIdResult authResult = task.getResult();
        String fcmToken = authResult.getToken();
    } else {
        // Task failed with an exception
        Exception exception = task.getException();
    }
}
});

Also, the FirebaseInstanceIdService Class is deprecated and they came up with onNewToken method in FireBaseMessagingService as replacement for onTokenRefresh,

you can refer to the release notes here, https://firebase.google.com/support/release-notes/android

@Override
public void onNewToken(String s) {
    super.onNewToken(s);
    Use this code logic to send the info to your server.
    //sendRegistrationToServer(s);
}
Manoj Kumar
  • 310
  • 4
  • 12
4

FirebaseInstanceIdService is now deprecated. you should get the Token in the onNewToken method in the FirebaseMessagingService.

Check out the docs

nir
  • 272
  • 1
  • 11
2

I have an update about "Firebase Cloud Messaging token" which I could get an information.

I really wanted to know about that change so just sent a mail to Support team. The Firebase Cloud Messaging token will get back to Server key soon again. There will be nothing to change. We can see Server key again after soon.

stop-cran
  • 3,546
  • 2
  • 25
  • 40
PM11
  • 59
  • 5
  • All that will change is the label in the [Cloud Messaging panel of the Project Settings](https://console.firebase.google.com/project/_/settings/cloudmessaging). The value will remain as you see it now. Sorry about any confusion the new label may have caused. – Frank van Puffelen Nov 25 '16 at 15:36