How to check if user is logged in with FB SDK 4.0 for Android?
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;
}
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! =]
My dilemma of using AccessToken and AccessTokenTracker for checking login status is that when AccessToken is ready and callback function of the tracker called but profile may be not ready yet, thus I cannot get or display Facebooker's name at that moment.
My solution is to check current profile != null and use its tracker for having Facebooker's name at the same time:
ProfileTracker fbProfileTracker = new ProfileTracker() {
@Override
protected void onCurrentProfileChanged(Profile oldProfile, Profile currentProfile) {
// User logged in or changed profile
}
};
Check login status and then get user name:
Profile profile = Profile.getCurrentProfile();
if (profile != null) {
Log.v(TAG, "Logged, user name=" + profile.getFirstName() + " " + profile.getLastName());
}