4

I am making an Android app that uses Firebase Cloud Messaging.

Whenever a new token is generated, the onTokenRefresh() function of a class extending FirebaseInstanceIdService is called.

However I noticed that the first time the token is generated, this function is not called. I want to send the first token to my Server. How can I implement this?

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Yash Jain
  • 376
  • 1
  • 3
  • 13
  • How did you notice that the **Token was generated first time** – Satyen Udeshi Jun 03 '16 at 07:42
  • I am printing Token eveytime in mainacticvity and also in OnTokenRefresh, It's showing from MainActivity but not from OnTokenRefresh – Yash Jain Jun 03 '16 at 10:20
  • @YashJain can u pls help me i am also getting null token in splash screen on very first time while internet is connected how u resolved ? – Erum Jun 09 '16 at 16:18
  • @Erum What I found after some analysis is that token generation by fcm takes some time maybe a minute or two. What I was doing in my First Activity was that I was printing Token before it had been generated so I was getting errors. So I changed my program accordingly. Once a token is generated no Error comes. Also try to store token value in PReferenceManager and then use them – Yash Jain Jun 10 '16 at 05:24
  • @YashJain so u directly obtain token inside onTokenRefresh METHOD of MyInstanceIDListenerService ? will this service automatically called ? may i need to call it by myself ? in splash activity – Erum Jun 10 '16 at 05:35
  • @Erum Yep it will be called automatically. But you can't expect when it will be called. – Yash Jain Jun 10 '16 at 07:19
  • @Erum Yep it will be called automatically but not in Splash Activity. You will get the token in MyInstanceIdListenerService where you should store it somewhere (example SharedPreferences) for later use. Because if there is no token available and if you execute getInstanceId().getToken() anywhere else your app won't work. So its better to take token at MyInstanceIdListenerService. Also you can't expect when token will be generated. – Yash Jain Jun 10 '16 at 07:25

1 Answers1

2

onTokenRefresh() just called when you have internet connection,after a token returned from FCM you can send it to your server

see https://stackoverflow.com/a/37546558/2032955

Community
  • 1
  • 1
Edalat Feizi
  • 1,371
  • 20
  • 32