简体   繁体   English

解决Firebase onTokenRefresh不能按时[Android]的解决方案是什么?

[英]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. 我对Android应用进行了编码,因此我需要设备令牌在首次启动时可用。 (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. 但是,我注意到当我需要设备令牌时,甚至没有调用onTokenRefresh。 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. 文档说:“ 在您的应用程序首次启动时,FCM SDK为客户端应用程序实例生成注册令牌。如果要定位单个设备或创建设备组,则需要通过扩展FirebaseInstanceIdService来访问此令牌。 ” ,我注意到它不是在我需要的时候准时生成的,并且似乎无法保证在我需要它时可以使用它。

Please advise. 请指教。 Thanks! 谢谢!

You could call FirebaseInstanceId.getInstance().getToken() everytime you need the token. 您可以在每次需要令牌时调用FirebaseInstanceId.getInstance().getToken() 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. 您可以使用sharedpreference存储此令牌,以后可以使用。 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 . - 这可能是避免使用null值的最安全解决方案

In my sense update user info all time after app launching (if token value not null) and store token value in sharedpreference inside 就我而言,在应用启动后始终会更新用户信息(如果令牌值不为null)并将令牌值存储在内部的sharedpreference中

onTokenRefresh() 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 只需在启动器活动的onCreate方法中使用它

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

and pass this id where you wannna use 并在您要使用的地方传递此ID

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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