Facebook AccessToken.getAccessToken is null on opening of app even after first login

Rohit Goyal picture Rohit Goyal · Mar 31, 2015 · Viewed 17.6k times · Source

I have integrated latest Facebook android sdk (Sdk 4.0). This is the code I have added in my onCreate method.

FacebookSdk.sdkInitialize(this.getApplicationContext());
            callbackManager = CallbackManager.Factory.create();
            if(AccessToken.getCurrentAccessToken()!=null){
                Log.d(FBTAG,"facebook already logged in");
                isFBLogin = true;
            }
            LoginManager.getInstance().registerCallback(callbackManager,
                    new FacebookCallback<LoginResult>() {
                        @Override
                        public void onSuccess(LoginResult loginResult) {
                            // App code
                            Log.d(FBTAG,"facebook log in");
                            isFBLogin = true;
                        }

                        @Override
                        public void onCancel() {
                             // App code
                            isFBLogin = false;
                        }

                        @Override
                        public void onError(FacebookException error) {
                            isFBLogin = false;
                            Log.d(FBTAG,"facebook login error: "+error);
                            // App code

                        }
            });

And this is the code I have used for onClickLogin

public void onClickLogin() {
        LoginManager.getInstance().logInWithPublishPermissions(this, PERMISSIONS);
    }

I am able to login by clicking on the login button and processing onClickLogin function. Now next time I am opening the app the app I am checking for AccessToken.getAccessToken to check if the user is already logged in at facebook but it is always coming as null. Isn't there anyway in the new sdk to login in the background so that I don't have to ask the user to login always like it used to be in the previous version in session class.

Answer

Frank picture Frank · Dec 30, 2015

You can also add an InitializeCallback to the sdkInitialize and check the AccessToken inside the callback:

FacebookSdk.sdkInitialize(getApplicationContext(), new FacebookSdk.InitializeCallback() {
        @Override
        public void onInitialized() {
            if(AccessToken.getCurrentAccessToken() == null){
                System.out.println("not logged in yet");
            } else {
                System.out.println("Logged in");
            }
        }
    });