How to check if user is logged in with FB SDK 4.0 for Android?

Felipe picture Felipe · Mar 27, 2015 · Viewed 74.3k times · Source

A few days ago I implemented FB Login to my APP, and today I found out that most of the things I have implemented are now deprecated.

Before, I was using Session to see if the user was logged in or not. However, that doesn't work with the new SDK.

According to their docs, we can use AccessToken.getCurrentAccessToken() and Profile.getCurrentProfile() to check if the user is already logged in, but I could not make use of those.

I tried something like this:

if(AccessToken.getCurrentAccessToken() == null)

I wonder if that would work if I could use it inside of this (which is also provided by FB):

LoginManager.getInstance().registerCallback(callbackManager, new LoginManager.Callback() {...});

However, I get a "Cannot resolve symbol 'Callback'".

EDIT!!!!!!

Alright, so I was able to check if the user is logged in by using the following:

On onCreate:

accessTokenTracker = new AccessTokenTracker() {
        @Override
        protected void onCurrentAccessTokenChanged(AccessToken oldAccessToken, AccessToken newAccessToken) {
            updateWithToken(newAccessToken);
        }
    };

Then, that calles my updateWithToken method:

private void updateWithToken(AccessToken currentAccessToken) {
    if (currentAccessToken != null) {

            LOAD ACTIVITY A!

    } else {

            LOAD ACTIVITY B!
    }
}

Now, the problem is: If the user has used the application and hasn logged in before, I can check for that! But if it is the first time that the user is using the app, updateWithToken is never called by my AccessTokenTracker.

I'd really appreciate if someone could help.

Thanks!

Answer

Felipe Mosso picture Felipe Mosso · May 5, 2015

A much simpler solution worked for my case (I don't know if this is the more elegant way though):

public boolean isLoggedIn() {
    AccessToken accessToken = AccessToken.getCurrentAccessToken();
    return accessToken != null;
}