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

75,754

Solution 1

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! =]

Solution 2

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;
}

Solution 3

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());
}

Solution 4

You can use the same way Felipe mentioned in his answer or you can use the other two ways. But it seems AccessTokenTracker is the convenient way, since it helps you to track the access tokens (use with ProfileTracker class)

  1. If you are using a custom button for your login use LoginManager call back

For example

In your layout xml

    <Button
        android:id="@+id/my_facebook_button"
        android:background="@drawable/btnfacebook"
        android:onClick="facebookLogin"/>

In your Activity

    //Custom Button
    Button myFacebookButton = (Button) findViewById(R.id.my_facebook_button);

The button onclick Listener

public void facebookLogin(View view) {
        LoginManager.getInstance().logInWithReadPermissions(this, Arrays.asList("public_profile", "user_friends"));
    }

At the end the LoginManager Callback

 //Create callback manager to handle login response
        CallbackManager callbackManager = CallbackManager.Factory.create();

       LoginManager.getInstance().registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
           @Override
           public void onSuccess(LoginResult loginResult) {
               Log.i(TAG, "LoginManager FacebookCallback onSuccess");
               if(loginResult.getAccessToken() != null) {
                   Log.i(TAG, "Access Token:: " + loginResult.getAccessToken());
                   facebookSuccess();
               }
           }

           @Override
           public void onCancel() {
               Log.i(TAG, "LoginManager FacebookCallback onCancel");
           }

           @Override
           public void onError(FacebookException e) {
               Log.i(TAG, "LoginManager FacebookCallback onError");
           }
       });
  1. If you are using the button (com.facebook.login.widget.LoginButton) provided in SDK use LoginButton callback (This is crealy detailed in their reference doc - https://developers.facebook.com/docs/facebook-login/android/v2.3)

For example

In your layout xml

<com.facebook.login.widget.LoginButton
                android:id="@+id/login_button"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center_horizontal"/>

In your activity

    //Facebook SDK provided LoginButton
    LoginButton loginButton = (LoginButton) findViewById(R.id.login_button);
    loginButton.setReadPermissions("user_friends");
    //Callback registration
    loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
        @Override
        public void onSuccess(LoginResult loginResult) {
            // App code
            Log.i(TAG, "LoginButton FacebookCallback onSuccess");
            if(loginResult.getAccessToken() != null){
                Log.i(TAG, "Access Token:: "+loginResult.getAccessToken());
                facebookSuccess();
            }

        }

        @Override
        public void onCancel() {
            // App code
            Log.i(TAG, "LoginButton FacebookCallback onCancel");
        }

        @Override
        public void onError(FacebookException exception) {
            // App code
            Log.i(TAG, "LoginButton FacebookCallback onError:: "+exception.getMessage());
            Log.i(TAG,"Exception:: "+exception.getStackTrace());
        }
    });

Dont forget to call callbackManager.onActivityResult(requestCode, resultCode, data); in your Activity onActivityResult()

Solution 5

According to facebook documentation you can do this by:

AccessToken accessToken = AccessToken.getCurrentAccessToken();
boolean isLoggedIn = accessToken != null && !accessToken.isExpired();
Share:
75,754
Felipe
Author by

Felipe

Updated on July 05, 2022

Comments

  • Felipe
    Felipe almost 2 years

    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!

  • RogerSmith
    RogerSmith about 9 years
    I've done everything in option 2. After I click the FB login button and click ok on their activity my app is relaunched. It hits my splash screen first which moves me to the activity where the login button is. The FB login button still says Log in with Facebook. Any ideas?
  • Skynet
    Skynet about 9 years
    I am using a different fragment for login purpose and a different fragment for posting, I wonder if I have to save the access token as a global state.
  • Andre Figueiredo
    Andre Figueiredo almost 9 years
    This should be the accepted solution. Also, I've double checked that it's not expired (.isExpired()).
  • u3l
    u3l almost 9 years
    This doesn't seem to work for me -- it is null even when I am logged in.
  • S-K'
    S-K' almost 9 years
    This is null even when I am logged in too
  • klimat
    klimat almost 9 years
    The reason AccessToken.getCurrentAccessToken() is null sometimes is onCurrentAccessTokenChanged is called async. You have to wait for it for the first time. Then you can use AccessToken.getCurrentAccessToken()
  • SpyZip
    SpyZip over 8 years
    If null, you need to Track Access Tokens developers.facebook.com/docs/facebook-login/android/v2.2
  • Anshul Tyagi
    Anshul Tyagi over 8 years
    But it didn't work when I tried to hide a button after getting logout from Facebook.
  • Konstantin Konopko
    Konstantin Konopko over 8 years
    This doesn't works for me. I'm using LoginButtonbut can't receive no one FB callback.
  • Konstantin Konopko
    Konstantin Konopko over 8 years
    @RogerSmith Also can't get any FB callbacks
  • Konstantin Konopko
    Konstantin Konopko over 8 years
    @sirvon the problem solved by setting up FB login activity as launch activity
  • Simon
    Simon over 8 years
    thanks - i had a bit of a problem trying to get the fb login accessToken to stick properly and this piece of code allowed it to remember i have logged in.
  • Mohamed ALOUANE
    Mohamed ALOUANE over 8 years
    Dont forget to call callbackManager.onActivityResult(requestCode, resultCode, data); in your Activity onActivityResult()
  • Ashraf Alshahawy
    Ashraf Alshahawy about 8 years
    Knowing that AcessToken.getCurrentAccessToken(); will return null if the user cleared device memory, for example via long press on Menu button and selecting closing all, or any other method.
  • Tara
    Tara about 8 years
    accessTokenTracker code has to be added before onCreate() and FB SDK has to initialized before setContectView() of onCreate()?
  • Thom
    Thom over 7 years
    Thanks., Profile.getCurrentProfile(); working fine for me :)
  • sanjeev
    sanjeev almost 6 years
    Well although this did work for moving to new activity. I don't seem to quite understand why the email and other details don't seem to be displayed. Nevertheless, the details are passed when i login for the first time.
  • zelig74
    zelig74 almost 4 years
    This only seems to work, according to provided doc, when "user is logged into the Facebook for Android app on the same device". I am afraid we cannot rely on this fact.