Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I access Firebase tokens outside of the FirebaseInstanceIdService?

I'm upgrading from GCM to FCM. What is the proper way to obtain a Firebase device token outside of onTokenRefresh?

I'm trying to get the device token so that I can re-enable it on my server at a later time. I initially get device token by following the documentation shown here for Method 1. However when I attempt to access the device token directly via method 2 I get a different token. Am I retrieving the device token incorrectly in method 2?

Method 1: inside of FirebaseInstanceIdService.onTokenRefresh()

String refreshedToken = FirebaseInstanceId.getInstance().getToken();

Method 2: Direct access to the device token

FirebaseInstanceId instanceID = FirebaseInstanceId.getInstance();
String registrationToken = instanceID.getToken(this.projectNumber, "FCM");
like image 254
David Truong Avatar asked Mar 09 '17 00:03

David Truong


People also ask

What can I use instead of Firebaseinstanceid?

Firebase Instance ID has been replaced with FirebaseInstallations for app instance identifiers and FirebaseMessaging. getToken() for FCM registration tokens. Firebase Instance ID provides a unique identifier for each app instance and a mechanism to authenticate and authorize actions (example: sending FCM messages).

How can I get token from Firebase?

The Firebase Admin SDK has a built-in method for verifying and decoding ID tokens. If the provided ID token has the correct format, is not expired, and is properly signed, the method returns the decoded ID token. You can grab the uid of the user or device from the decoded token.

How do I manage FCM tokens?

When a user register/sign in, the mobile app will call register device API . This API creates a row in the device table. The application server uses the token in the device table to send push notification.


1 Answers

Just to explain what is happening in Method 1. It is suggested to get the token inside onTokenRefresh() since when this method is triggered, it means that the previous token got invalidated. From the docs:

Called when the system determines that the tokens need to be refreshed. The application should call getToken() and send the tokens to all application servers.

For Method #2, you're calling getToken(String authorizedEntity, String scope), instead of getToken(). The one with two parameters is commonly used when setting up your app to receive messages from multiple senders.

For each call to getToken(String authorizedEntity, String scope) with a different project ID (authorizedEntity) it will return a different token.

Just replace your Method 2 with the same call in Method 1, like so:

String registrationToken = FirebaseInstanceId.getInstance().getToken();

and you should be able to retrieve the designated token. The token is often retrieved in the onCreate() of your initial activity.

like image 161
AL. Avatar answered Oct 26 '22 23:10

AL.