mumu
mumu

Reputation: 3

Firebase Token ID return null value

I am working on firebase FCM to send message from device to device. However, I am stuck at retrieving token ID. I have tried with " FirebaseInstanceId.getInstance().getToken();" but not able to get token ID. It keeps returning me null value.

I found some post saying that getToken() is deprecated, have to use getInstanceId() instead. However, my android studio failed to resolve this getInstanceId() and onNewToken(). Is there any way to get firebase TokenID?

Upvotes: 0

Views: 3320

Answers (2)

sree
sree

Reputation: 783

In FirebaseMessagingService class add below code.

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

   }
    });
}

Upvotes: 0

Gourango Sutradhar
Gourango Sutradhar

Reputation: 1619

Access the device registration token:

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 creating a new class which extends FirebaseInstanceIdService . In that class, call getToken within 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);

    // If you want to send messages to this application instance or
    // manage this apps subscriptions on the server side, send the
    // Instance ID token to your app server.
    sendRegistrationToServer(refreshedToken);
}

Also add the service to your manifest file:

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

The onTokenRefresh callback 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 have obtained the token, you can send it to your app server. See the Instance ID API reference for full detail on the API.

(From firebase reference)

Upvotes: 1

Related Questions