34

I'm have a feature on my Android app where the user authorizes the app and shares a link.

I also need to give an option for the user to logout of facebook and I need to conditionally disable this button if the user is not logged int (or not authorized the app).

I can't seem to find the API call on the Android SDK that would let me ask FB if the user is logged in or not.

What I have found is getAccessExpires():

Retrieve the current session's expiration time (in milliseconds since Unix epoch), or 0 if the session doesn't expire or doesn't exist.

Will checking if the session equals 0 be the way to go? Or is there something I'm missing?

Jay Sidri
  • 6,271
  • 3
  • 43
  • 62
  • 1
    Have you seen this doc - https://developers.facebook.com/docs/reference/androidsdk/authentication/ ? – deesarus Sep 13 '12 at 18:36

10 Answers10

54

Facebook SDK 4.x versions have a different method now:

boolean loggedIn = AccessToken.getCurrentAccessToken() != null;

or

by using functions

boolean loggedIn;
//...
loggedIn = isFacebookLoggedIn();
//...
public boolean isFacebookLoggedIn(){
    return AccessToken.getCurrentAccessToken() != null;
}

Check this link for better reference https://developers.facebook.com/docs/facebook-login/android check this heading too "Access Tokens and Profiles" it says "You can see if a person is already logged in by checking AccessToken.getCurrentAccessToken() and Profile.getCurrentProfile()

Diljeet
  • 1,896
  • 20
  • 24
  • 1
    It always keeps on changing, lets see what it will be next. – Shajeel Afzal Apr 24 '15 at 10:36
  • 4
    I voted this up, but apparently, after restarting the app, the `getCurrentAccessToken()` still returns null, while looking at the LoginButton: it says LogOut. What are we missing here? – CularBytes May 17 '15 at 17:53
  • @RageCompex : well it should not return null, this never happened to me, maybe you should enable "Single Sign On" & "Deep Linking" from your app settings on developers.facebook.com So you don't have to sign in again and again. Also check the code from the Login guide from facebook android sdk – Diljeet May 18 '15 at 12:43
  • I had this code on application start, there it did not work, while it did work in an Activity, very wierd – CularBytes May 18 '15 at 13:19
  • @lacas Check this link for better reference https://developers.facebook.com/docs/facebook-login/android/v2.3 in any case if you are missing something check this out, check this heading too "Access Tokens and Profiles" it says "You can see if a person is already logged in by checking AccessToken.getCurrentAccessToken() and Profile.getCurrentProfile()" – Diljeet Jun 10 '15 at 19:12
  • @RageCompex : same issue, after restart `AccessToken.getCurrentAccessToken()` returns null even though button shows `Log out`. `Profile.getCurrentProfile` on the other hand is non null and works for me, (Change of "Single Sign On" & "Deep Linking" didn't solve my issue). – Mateusz Kubuszok Dec 23 '15 at 19:38
  • @Diljeet 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. – Ashraf Alshahawy Mar 17 '16 at 00:10
  • @Astrount Hello sir i developed a Facebook App long time ago, so i am not sure. I think the response is cached in android app's private data, so if you close/kill the app the response will not return null, it will return null if you clear the data of the app from Settings->Apps->YourApp. Please try it and update your comment with confirmation, so that it can help others. Good Day – Diljeet Mar 17 '16 at 10:25
  • @Diljeet Thank you for your feedback, I'll recheck and get back to you with the result. Regards – Ashraf Alshahawy Mar 17 '16 at 14:02
  • 1
    @Diljeet I rechecked & confirmed what I said above, even after closing my application and clearing RAM it causes the access token to be null when called, you have to refresh the access token when starting the application again / later. Thank you. – Ashraf Alshahawy Mar 18 '16 at 04:38
48

I struggled to find a simple answer to this in the FB docs. Using the Facebook SDK version 3.0 I think there are two ways to check if a user is logged in.

1) Use Session.isOpened()

To use this method you need to retrieve the active session with getActiveSession() and then (here's the confusing part) decipher if the session is in a state where the user is logged in or not. I think the only thing that matters for a logged in user is if the session isOpened(). So if the session is not null and it is open then the user is logged in. In all other cases the user is logged out (keep in mind Session can have states other than opened and closed).

public boolean isLoggedIn() {
    Session session = Session.getActiveSession();
    return (session != null && session.isOpened());
}

There's another way to write this function, detailed in this answer, but I'm not sure which approach is more clear or "best practice".

2) Constantly monitor status changes with Session.StatusCallback and UiLifecycleHelper

If you follow this tutorial you'll setup the UiLifecycleHelper and register a Session.StatusCallback object with it upon instantiation. There's a callback method, call(), which you override in Session.StatusCallback which will supposedly be called anytime the user logs in/out. Within that method maybe you can keep track of whether the user is logged in or not. Maybe something like this:

private boolean isLoggedIn = false; // by default assume not logged in

private Session.StatusCallback callback = new Session.StatusCallback() {
    @Override
    public void call(Session session, SessionState state, Exception exception) {
        if (state.isOpened()) { //note: I think session.isOpened() is the same
            isLoggedIn = true;
        } else if (state.isClosed()) {
            isLoggedIn = false;
        }
    }
};

public boolean isLoggedIn() {
    return isLoggedIn;
}

I think method 1 is simpler and probably the better choice.

As a side note can anyone shed light on why the tutorial likes to call state.isOpened() instead of session.isOpened() since both seem to be interchangeable (session.isOpened() seems to just call through to the state version anyway).

Community
  • 1
  • 1
Tony Chan
  • 8,017
  • 4
  • 50
  • 49
  • In what scenario would you use openActiveSessionFromCache – Madhur Ahuja Oct 22 '13 at 06:04
  • @MadhurAhuja I'm not really sure. I haven't played around with the FB SDK much as I only really needed the login functionality of it. – Tony Chan Oct 22 '13 at 07:50
  • I have read and used the code on the first option using session.IsOpened(). Now I'm encountering a problem. This works well if the facebook logs in via the device's browser. But when logged in on the facebook app. The session is always null. Any ideas on how to solve this? Here's a link of my question http://stackoverflow.com/questions/22407482/facebook-login-via-app-vs-via-device-browser-in-android-app – Luke Villanueva Mar 14 '14 at 14:24
  • Just nitpicking but, why not just `return session != null && session.isOpened()` and `isLoggedIn = state.isOpened()`. – mr5 Jun 25 '14 at 06:08
  • @mr5 Good suggestions. I've edited the answer to streamline the code. No real reason I had it the other way, it was just easy for me to follow the logic at the time. I like your suggestion though, more efficient. As for the second method/suggestion, I'm going to leave it as my original answer, only because `SessionState` can have other states other than *open* or *closed* which I haven't looked into, so I want to only change `isLoggedIn` if it is explicitly open/closed. If anyone can confirm the other states mean the user is logged out then I'll gladly change the answer. – Tony Chan Jun 26 '14 at 22:42
  • I am using 3.23.0 version. Session.getActiveSession() always returning null when I am checking in splash screen though user is logged in previously. Y? – Prashanth Debbadwar Oct 15 '15 at 09:09
6

Note to readers: This is now deprecated in the new FB 3.0 SDK.

facebook.isSessionValid() returns true if user is logged in, false if not.

SMR
  • 6,628
  • 2
  • 35
  • 56
Jesse Chen
  • 4,928
  • 1
  • 20
  • 20
3
Session.getActiveSession().isOpened()

returns true if user is logged in, false if not

Zennichimaro
  • 5,236
  • 6
  • 54
  • 78
3

Android Studio with :

compile 'com.facebook.android:facebook-android-sdk:4.0.1'

then check login like as:

private void facebookPost() {
    //check login
    AccessToken accessToken = AccessToken.getCurrentAccessToken();
    if (accessToken == null) {
        Log.d(TAG, ">>>" + "Signed Out");
    } else {
        Log.d(TAG, ">>>" + "Signed In");
    }
}
Son Nguyen Thanh
  • 1,199
  • 15
  • 19
2

@diljeet was right. https://stackoverflow.com/a/29375963/859330

In addition, use

return AccessToken.getAccessToken() != null && Profile.getCurrentProfile()!=null;

It always works this way.

Community
  • 1
  • 1
CanCoder
  • 1,073
  • 14
  • 20
1

For Facebook Android SDK 4.x you have to use the "AccessToken.getCurrentAccessToken()" as said by @Diljeet but his check didn't work for me, I finally checked it by doing:

Activity "onCreate":

facebookAccessToken = AccessToken.getCurrentAccessToken();

To check if the session is still active (I made it in the "onResume" method but do it where you need):

  if(facebookAccessToken != null){
        sessionExpired = facebookAccessToken.isExpired();
  }else{
        sessionExpired = true;
  }

More info in https://developers.facebook.com/docs/facebook-login/android

Alberto Méndez
  • 1,044
  • 14
  • 31
0

This seems to be working quite well with the new sdk.

private boolean isFacebookLoggedIn(){
    Session session = Session.getActiveSession();

    if (session != null) {
        //Session can be open, check for valid token
        if (!session.isClosed()) {
            if(!session.getAccessToken().equalsIgnoreCase("")){
                return true;
            }
        }
    }
    return false;
}
DeaMon1
  • 572
  • 5
  • 10
0

I had the same issue. Here is my solution using SDK 4.0:

First of all, in your activity dealing with login check, be sure to call this primary:

        FacebookSdk.sdkInitialize(this.getApplicationContext());

In your onCreate method put this :

updateWithToken(AccessToken.getCurrentAccessToken());

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

Then add the method called:

private void updateWithToken(AccessToken currentAccessToken) {
    if (currentAccessToken != null) {
        fillUIWithFacebookInfos(handler);
    } else {
        login();
    }
}

This way will handle the already logged in user and the newly logged in user.

Thomas L.
  • 1,294
  • 9
  • 13
0

I was using FB sdk for just for login.. Facebook developers reject my app, Because whenever user login, I send logout.. I dont matter user profile data... I just use FB for login.. FB tells if user login... dont send lgout...

I find Hacking way... Now my app doesnot send logout whenever user login.... Whatever user login with,Google,Facebook,or normal.. When they click logout... In this three condition I use LoginManager.getInstance().logOut();

No matter which platform they use... There is no crash :)

Ucdemir
  • 2,852
  • 2
  • 26
  • 44