简体   繁体   中英

What is the solution to Firebase onTokenRefresh not being called on-time [Android]?

I have coded my Android app in such a way that I need the device token to be available upon first launch. (The user will login/signup and I need to send this token together with the login/signup request to the server.)

However, I noticed that onTokenRefresh is not yet even called when I need the device token. It is the same in both the emulator and a real device. What can be the solution to my problem? Can I obtain a device token on demand? Or could it be something to do with requesting permission to force a device token to be generated?

The documentation says " On initial startup of your app, the FCM SDK generates a registration token for the client app instance. If you want to target single devices or create device groups, you'll need to access this token by extending FirebaseInstanceIdService. " However, I noticed that it is not generated on time when I need it and there's seems to be no guarantee that it is available when I need it.

Please advise. Thanks!

You could call FirebaseInstanceId.getInstance().getToken() everytime you need the token. It works pretty fine for me.

It is perhaps sure that token would be generated at very starting of the app. This token would not be re-generate / re-create without some conditions to fulfill. You can store this token using sharedpreference and can use later. I am doing like this and seems getting token for users when I need.

****If token refresh takes that much long time then you could update user info later after getting token. - This could be the safest solution to avoid null value .

In my sense update user info all time after app launching (if token value not null) and store token value in sharedpreference inside

onTokenRefresh()

that user value would be always updated if it changes in any situation.

Just use this in your onCreate method of your launcher activity

String id=FirebaseInstanceId.getInstance().getToken()

and pass this id where you wannna use

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM