How to get current access token in Facebook Androi

2020-07-10 08:58发布

问题:

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()) {

        }
    }
}

回答1:

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



回答2:

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

}


回答3:

Did you call the Facebook SDK's onActivityResult() from your activity's ? I also encountered same problem and resolved by adding this onActivityResult() callback.