Home > Enterprise >  Can Firebase's onNewToken() fire when the app is backgrounded or killed?
Can Firebase's onNewToken() fire when the app is backgrounded or killed?

Time:07-19

I am trying to understand the behavior of Firebase Cloud Messaging's client app onNewToken method.

Within the documentation you see several references to several events which can cause FCM to regenerate the token but no comprehensive list. Some samplings:

On initial startup of your app, the FCM SDK generates a registration token for the client app instance. ... This section describes how to retrieve the token and how to monitor changes to the token. Because the token could be rotated after initial startup, you are strongly recommended to retrieve the latest updated registration token.

The registration token may change when

  • The app is restored on a new device
  • The user uninstalls/reinstall the app
  • The user clears app data [1]

Called if the FCM registration token is updated. This may occur if the security of the previous token had been compromised [2]

Suffice to say the token is considered unstable and we should do our due diligence in getting the most up-to-date-token to our backend.

My question comes down to, what happens if these "refresh" events occur when 1) the app is backgrounded or 2) killed. Will onNewToken() still fire in both of these cases?

The FCM best practices references setting up a monthly job to check the latest token

Add app logic in your client app to retrieve the current token using the appropriate API call (such as token(completion): for Apple platforms or getToken() for Android) and then send the current token to your app server for storage (with timestamp). This could be a monthly job configured to cover all clients/tokens [3]

Is the intent behind this to capture the user devices which haven't launched your app in a while? How do you best keep registrations up-to-date for inactive users -- or is it sufficient to simply check the latest token always onCreate() in the MainActivity?

CodePudding user response:

The onNewToken callback can indeed be invoked when the app is backgrounded, which is why it is implemented in a Service.

As far as I know it won't be invoked when the application is killed, as no parts of the app remain active when that happens. So if the app is killed, you will only get the new token once it restarts.

To ensure you work with the latest token for a device, you should implement onNewToken and check for updates to the token when the app restarts (typically in its first/main activity).

  • Related