Felipe Felipe - 6 months ago 98
Android Question

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

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

I got it!

First, make sure you have initialized your FB SDK. Second, add the following:

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

This will be called when there's a change on the Current Access Tokes. Meaning, this will only help you if the user is already logged in.

Next, we add this to our onCreate() method:

updateWithToken(AccessToken.getCurrentAccessToken());

Then of course, our updateWithToken() method:

private void updateWithToken(AccessToken currentAccessToken) {

    if (currentAccessToken != null) {
        new Handler().postDelayed(new Runnable() {

            @Override
            public void run() {
                Intent i = new Intent(SplashScreen.this, GeekTrivia.class);
                startActivity(i);

                finish();
            }
        }, SPLASH_TIME_OUT);
    } else {
        new Handler().postDelayed(new Runnable() {

            @Override
            public void run() {
                Intent i = new Intent(SplashScreen.this, Login.class);
                startActivity(i);

                finish();
            }
        }, SPLASH_TIME_OUT);
    }
}

That did it for me! =]