Android Question Firebase Token sometimes empty

EricDalton

New Member
Hi,
I’m using FirebaseMessaging in my B4A project.
Below is my Starter service:
B4X:
#Region  Service Attributes
    #StartAtBoot: False
    #ExcludeFromLibrary: True
#End Region

Sub Process_Globals
    Public fcm As FirebaseMessaging
End Sub

Sub Service_Create
    fcm.Initialize("fcm")
    fcm.SubscribeToTopic("general")
End Sub

Sub Service_Start (StartingIntent As Intent)
    Service.StopAutomaticForeground
End Sub

Sub Service_TaskRemoved
End Sub

Sub Application_Error (Error As Exception, StackTrace As String) As Boolean
    Return True
End Sub

Sub Service_Destroy
End Sub

Sub fcm_TokenRefresh (Token As String)
    Log(Token)
End Sub
And in another module Code I use this function to get the token:

B4X:
Sub GetFirebaseToken As String
    Return Starter.fcm.Token
End Sub
I call this from the Splash Screen to send the token to my server.
Sometimes the result of MyCodes.GetFirebaseToken is empty.
For example:
About 1 out of 4–5 launches, the Token is still "" at Splash Screen.
If the device has no internet on first run, the token is also empty.
It seems Firebase needs some time before generating the token.
What is the recommended way in B4A to ensure that the Firebase token is available before sending it to the server? How should I handle situations where the token is generated late, cases where the token is empty on app start, and scenarios where no internet connection is available on the first launch? Is there a correct event or a recommended pattern for waiting until the token is ready?
Any help would be appreciated. Thanks! 🙏
 

DonManfred

Expert
Licensed User
Longtime User
It takes some time for the token to be ready

B4X:
Sub Service_Create
    fcm.Initialize("fcm")
    fcm.SubscribeToTopic("general")
    Do While fcm.Token = ""
        'Log("Sleep250")
        Sleep(250)     
    Loop
End Sub
 
Upvote 1
Top