Skip to main content

How to LogOut from app with Facebook sdk 4 in android: Logout from app

Source Link
giozh
  • 10.1k
  • 33
  • 111
  • 190

Facebook sdk 4 android: Logout from app

I'm updating an app that use facebook sdk, but i'm facing some problems, and official documentation is too poor. On my app, user can log in with facebook or with a normal account (stored on my server), and this options are showed on app startup. Obviously user can also log out and log in with another account (facebook or not), and i have a problem with facebook logout. In fact i'm not able to logout user connected with facebook account. As i've noticed after a lot of attempts, all changes about facebook status are tracked by AccessTokenTracker and ProfileTracker, that should be instantiated only once at startup. I show (and explain) my code. This is code of my login FragmentActivity that check if user was already logged in (with facebook or with dedicated account), and if yes, show next activity, else show fragment for choose access options:

@Override
protected void onCreate(Bundle savedInstanceState) {
    FacebookSdk.sdkInitialize(this.getApplicationContext());
    callbackManager = CallbackManager.Factory.create();

        accessTokenTracker = new AccessTokenTracker() {
            @Override
            protected void onCurrentAccessTokenChanged(AccessToken oldAccessToken, AccessToken currentAccessToken) {
                if (currentAccessToken != null) {
                    Log.i("LOGINACTIVITY", "token tracker, current token valid");
                    AccessToken token = AccessToken.getCurrentAccessToken();
                    //already logged with facebook, show next activity

                } else {
                    //check if current visible activity is logout activity
                    // that contains logout button
                    ActivityManager am = (ActivityManager) LoginActivity.this.getSystemService(ACTIVITY_SERVICE);
                    List<ActivityManager.RunningTaskInfo> taskInfo = am.getRunningTasks(1);

                    String top_activity = taskInfo.get(0).topActivity.getClassName();

                    if (top_activity.equals(getApplicationContext().getPackageName() + ".LogoutActivity")) {
                        //launch new login activity
                        LoginManager.getInstance().logOut();
                        getApplicationContext().startActivity(new Intent(getApplicationContext(),
                                LoginActivity.class).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
                       
                    }

                }
            }
        };

        accessTokenTracker.startTracking();

Now it happen that, when i press logout button, accesstoken tracker execute else branch so show login options it's showed, but for some reason app automatically login again with facebook (it's invoked if branch of TokenTracker), so user is not able to logout from facebook. What's wrong?