Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: Firebase token is null at first run

I am using FCM to provide notifications in my app. Everything worked well, but now I realised that, when I install my application using Android Studio (not from GooglePlay) the token is null at first run. When I close my app and restart it, the token is not null anymore. What cause this problem and how can I avoid it?

InstanceIDService:

public class InstanceIDService extends FirebaseInstanceIdService {      @Override     public void onTokenRefresh() {          String token = FirebaseInstanceId.getInstance().getToken();         registerToken(token);     }      private void registerToken(String token) {          OkHttpClient client = new OkHttpClient();         RequestBody body = new FormBody.Builder()                 .add("Token",token)                 .build();          Request request = new Request.Builder()                 .url("url_to_registration_script")                 .post(body)                 .build();          try {             client.newCall(request).execute();         } catch (IOException e) {             e.printStackTrace();         }     } } 

In MainActivity:

FirebaseMessaging.getInstance().subscribeToTopic("topic"); String token = FirebaseInstanceId.getInstance().getToken(); Log.d("TOKEN", token); 

Last log returns null when app is installed and started for the first time

Registration script:

 <?php   if (isset($_POST["Token"])) {         $_uv_Token=$_POST["Token"];        $conn = mysqli_connect("localhost","user","pass","db") or die("Error connecting");        $q="INSERT INTO users (Token) VALUES ( '$_uv_Token') "           ." ON DUPLICATE KEY UPDATE Token = '$_uv_Token';";    mysqli_query($conn,$q) or die(mysqli_error($conn));   mysqli_close($conn); } ?> 
like image 238
Matej Košút Avatar asked Jun 15 '16 13:06

Matej Košút


2 Answers

The token is fetched asynchronously on first app start. You have to wait for onTokenRefresh() to be called in your FirebaseInstanceIdService before the token can be accessed.

like image 121
patloew Avatar answered Sep 23 '22 23:09

patloew


uninstall the app from emulator and run again , so that the onTokenRefreshed method will be called again .

To check wether you are already registered and you just want to know the FCM TOken

String refreshedToken = FirebaseInstanceId.getInstance().getToken(); 

add the above line in MyFirebaseMessagingService class any where(in oncreate method ) and just Toast or log the refreshedToken.

like image 21
kashyap k bandi Avatar answered Sep 21 '22 23:09

kashyap k bandi