The events when the onTokenRefresh() is triggered is already included in the FirebaseInstanceIdService documentation:
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.
This will not be called very frequently, it is needed for key rotation and to handle Instance ID changes due to:
- App deletes Instance ID
- App is restored on a new device
- User uninstalls/reinstall the app
- User clears app data
The system will throttle the refresh event across all devices to avoid overloading application servers with token updates.
And as also specified, the FirebaseInstanceIdService class extends the Service class, which can run regardless if the app is in foreground or background.