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:

  • Google location API: request location updates with pending intent?
  • Radial Gradient for different dpi
  • FragmentPagerAdapter troubles and woes: Constructor Undefined
  • Where does Android store SQLite's database version?
  • Saving and retrieving data from sugar db without duplication
  • PlacePicker doesn't pick up material theme
  • 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);
    }
    ?>
    

    Related posts:

    How to Set Opacity (Alpha) for View in Android
    In java, how can I delete a sqlite table?
    Adapter with hasStableIds using GUIDs or Strings as Ids
    Android Studio - Ambiguous method call getClass()
    Android: AAC+ radio streaming doesn&#039;t work with MediaPlayer (Android 4.2.2 / Shoucast links...
    Android SDK - Not Scaling at Centre of Touch
  • What is the Maximum Size of the Volley-Library Request-Queue
  • Resizing ImageView to fit to aspect ratio
  • setOnClickListener on TextView
  • reading android jpeg EXIF metadata from picture callback
  • findViewByID returns null
  • Failed to load memtrack module -2
  • 7 Solutions collect form web for “Android: Firebase token is null at first run”

    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.

    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.

    Even I had the same issue. I had given the Log statement to print token in onCreate of my launcher activity. It takes time to refresh the token once you uninstall the app. Thats why you get null. You have to wait for a bit to get the token refreshed.

    I just fell in same issue and this is the way I fixed it. Call the block somewhere in onCreate() method of your activity. I want to sent the Token to my Parse server so you must change it based on your needs.

    This is the sample I followed.

    private void subscribeUserToParse() {
            String deviceToken = FirebaseInstanceId.getInstance().getToken();
            if (TextUtils.isEmpty(deviceToken)) {
                Intent intent = new Intent(this, MyFirebaseInstanceIDService.class);
                startService(intent);
                return;
            }
    
            User user = UserUtil.retrieveUserFromDB(mRealm);
            String objectId = user.getParseObjectId();
            if (!TextUtils.isEmpty(objectId)) {
                ParseUtils.subscribeWithUsersObjectId(objectId, deviceToken);
            }
        }
    

    I was facing the same problem. I looked through a lot of SO posts and other forums and I found a solution that worked for me. FCM documentation says to use this method to get a token.

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

    I found a post online (I apologize, I don’t remember which one. I found it a while ago) that used this method instead:

    String refreshedToken = FirebaseInstanceId.getInstance().getToken() (String authorizedEntity, String scope);
    

    FCM documentation describes the first method as:

    Return the master token for the default Firebase project.

    While the second one is described as:

    Returns a token that authorizes an Entity to perform an action on behalf of the application identified by Instance ID.
    This is similar to an OAuth2 token except, it applies to the application instance instead of a user.
    For example, to get a token that can be used to send messages to an application via FirebaseMessaging, set to the sender ID, and set to “FCM”.

    I have been looking into why the first method call takes a longer time to return a token, but I haven’t found an answer yet. Hope this helps.

    Just replace:

    String token = instanceID.getToken();
    

    with:

    String token = instanceID.getToken($SENDER_ID, "FCM");
    

    and it will work.

    Just adding this will work.

    if(regid == null) {
                regid = FirebaseInstanceId.getInstance().getToken();
            }
    
    Android Babe is a Google Android Fan, All about Android Phones, Android Wear, Android Dev and Android Games Apps and so on.