Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get current access token in Facebook Android SDK V4?

I want to check whether the user is logged in or not within the main FragmentActivity but although the user is logged in

AccessToken.getCurrentAccessToken()

returns null. What am I doing wrong in the code below ?

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    context = this;          
    FacebookSdk.sdkInitialize(context);
    callbackManager = CallbackManager.Factory.create();
    AccessToken accessToken = AccessToken.getCurrentAccessToken();
    if (accessToken != null) {
        if (!accessToken.isExpired()) {

        }
    }
}
like image 568
Sujit Maharjan Avatar asked Apr 24 '15 09:04

Sujit Maharjan


2 Answers

How is the user logging in, via the LoginButton? If so, it'll happen after they click the login button, so where you're checking is too early.

If they already logged in, then the access token is going to be deserialized from disk, however this is an async operation so that the UI thread is not blocked. You check it right after you initialize the Sdk, and the async operation is probably not completed yet. I suggest you use the AccessTokenTracker to respond when the AccessToken is loaded. Here's a sample that uses the AccessTokenTracker for your reference: https://github.com/facebook/facebook-android-sdk/blob/b384c0655fe96db71229bfdcb981a522f3f1e675/samples/Scrumptious/src/com/facebook/scrumptious/usersettings/UserSettingsFragment.java#L75

like image 182
Gokhan Caglar Avatar answered Nov 01 '22 09:11

Gokhan Caglar


Android Facebook sdk Initialization is take some time Initialize. so you need to wait just 100 milliseconds before calling AccessToken.getCurrentAccessToken()

once try this solution it is working for me

    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    context = this;
    FacebookSdk.sdkInitialize(context);

    new Handler().postDelayed(new Runnable() {
        @Override
        public void run() {

            callbackManager = CallbackManager.Factory.create();
            AccessToken accessToken = AccessToken.getCurrentAccessToken();
            if (accessToken != null) {
                if (!accessToken.isExpired()) {

                }
            }

        }
    }, 100);

}
like image 39
Anil Chandra Varma Dandu Avatar answered Nov 01 '22 10:11

Anil Chandra Varma Dandu