Search code examples
androidfacebookfacebook-android-sdkfacebook-access-token

How to get current Facebook access token on app start?


On app start I need to know if the user is logged in or not to show a login page or not.

My first try was to call AccessToken.getCurrentAccessToken(), but this doesn't work, see https://stackoverflow.com/a/29854249/1016472

My 2nd try was to use the AccessTokenTracker but this doesn't work too. To use the AccessTokenTracker I have to initialize the Facebook SDK first. But during this initialization the access token is send to the tracker. The tracker isn't created at this time and can't receive the token.

My 3rd try was to create my own AccessTokenTracker which looks like the original one. I created and registered it before I initialize the SDK. And now my tracker get's the token during this SDK initialization process.

With this knowledge I open a bug report at Facebook with the questions:

  • Why the AccessTokenTracker depends on the initialized SDK. I think this is a mistake.
  • What is the right way to see if a user is logged in or not on app start.

The answer from Facebook:

This doesn't look like bug. The AccessTokenTracker ::onCurrentAccessTokenChanged should let you know when the class has received a token.

I know that this is not working. And now I know there is no bug.

But how to solve my problem?

This doesn't work:

FacebookSdk.sdkInitialize(getApplicationContext());
mAccessTokenTracker = new AccessTokenTracker() {

    @Override
    protected void onCurrentAccessTokenChanged(AccessToken oldAccessToken, AccessToken currentAccessToken) {

        Timber.i("AccessTokenTracker oldAccessToken: " + oldAccessToken + " - currentAccessToken: " + currentAccessToken);
    }
};

Solution

  • You need to initialize the SDK first as you said. Then create the access token tracker, and then check the current access token via AccessToken.getCurrentAccessToken().

    If the SDK initializer is fast enough that the token is set before you can create the tracker, then your call of currentAccessToken will get the token. If the sdk initialization is slower than then tracker registration then the tracker will get the access token.