1

Our business logic requires us to instantiate Firebase during runtime. We fetch the Firebase credentials (App ID, API key etc.) from a default Firebase location after knowing the user's public key and create a Firebase instance using those credentials.

This means that there are two Firebase instances used within the app:

  1. The default "index" Firebase that gives us credentials for the second
  2. The actual Firebase that we intend to use from that point forward

The second Firebase is initialised like this:

FirebaseApp app = FirebaseApp.initializeApp(<context>, <options>, <app_label>);

Our problem is that the traditional method of retrieving the FCM token using the FirebaseInstanceIdService and onTokenRefresh() fails since the onTokenRefresh() method is called only by the first Firebase instance.

Directly calling String token = FirebaseInstanceId.getInstance(app).getToken(); returns null as it is never ready when called. We have even tried polling this to test if a token is generated at some point. No luck.

How can we generate an FCM token reliably from a Firebase instance instantiated during runtime?

AL.
  • 36,815
  • 10
  • 142
  • 281
Manikandan
  • 40
  • 7

1 Answers1

1

In general, only the traditional method of getting the token (getToken()) is the only one that refers to the main Firebase Instance. This can be called almost anywhere in your app (but is often called in the initial activity). This will return the token associated to the Sender ID that is seen in your google-services.json. It is also possible for this to return null if the token is still being generated. In cases like that, onTokenRefresh() is triggered upon generation.

However, if you intend to generate a FCM registration token for a different Firebase Project, you'll have to make use FirebaseIntsanceId.getInstance.getToken(String authorizedEntity, String scope), where authorizedEntity is the Sender ID of that different Firebase Project and scope is "FCM" (you can use FirebaseMessaging.INSTANCE_ID_SCOPE as default).

In short, you don't need to specify the Firebase Instance when generating a token.

Also see my answers here and here.

Community
  • 1
  • 1
AL.
  • 36,815
  • 10
  • 142
  • 281