PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, June 29, 2022

[FIXED] How to handle the logout button click in fb sdk 4.18.0?

 June 29, 2022     android, facebook-sdk-4.0     No comments   

Issue

I want to perform some function when the user logout from my app,in which he has logged in using facebook but on clicking the button the login onSuccess() is called ,the users gets logged in and a logout button comes to display..On clicking on the logout button the user is simply logged out but no specific funtion is called during this and hence i cannot handle it to perform some task on logging out.Please help me.Thanks in advance. I have used the facebook sdk 4.18.0.

this is my code for LoginActivity which contains button for google and facebook login.

public class LoginActivity extends AppCompatActivity implements View.OnClickListener, GoogleApiClient.OnConnectionFailedListener {

    private GoogleApiClient mGoogleApiClient;
    private SignInButton googleLoginButton;
    private Button btnSignOut;
    private Button btnRevokeAccess;
    private AccessTokenTracker tokenTracker;
    private ProfileTracker profileTracker;
    private TextView mText;
    private ImageView profile_pic;
    private ProgressDialog mProgressDialog;
    private LoginButton fbLoginButton;
    private GoogleSignInResult result1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        //FACEBOOK SDK
        FacebookSdk.sdkInitialize(getApplicationContext());
        mcallbackManager = CallbackManager.Factory.create();
        tokenTracker = new AccessTokenTracker() {
            @Override
            protected void onCurrentAccessTokenChanged(AccessToken oldAccessToken, AccessToken currentAccessToken) {

            }
        };
        profileTracker = new ProfileTracker() {
            @Override
            protected void onCurrentProfileChanged(Profile oldProfile, Profile currentProfile) {

            }
        };
        profileTracker.startTracking();
        tokenTracker.startTracking();
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        mText = (TextView) findViewById(R.id.txt);
        profile_pic = (ImageView) findViewById(R.id.profile_pic);
        googleLoginButton = (SignInButton) findViewById(R.id.google_login_button);
        btnSignOut = (Button) findViewById(R.id.btn_sign_out);
        btnRevokeAccess = (Button) findViewById(R.id.btn_revoke_access);
        fbLoginButton = (LoginButton) findViewById(R.id.fb_login_button);
        fbLoginButton.setReadPermissions("user_friends");
        fbLoginButton.registerCallback(mcallbackManager, callback);
        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });

        googleLoginButton.setOnClickListener(this);
        btnSignOut.setOnClickListener(this);
        btnRevokeAccess.setOnClickListener(this);

        GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN).requestProfile().requestId().requestEmail().build();
        mGoogleApiClient = new GoogleApiClient.Builder(this).enableAutoManage(this, this).addApi(Auth.GOOGLE_SIGN_IN_API, gso).build();

        googleLoginButton.setSize(SignInButton.SIZE_STANDARD);
        googleLoginButton.setScopes(gso.getScopeArray());
    }

    @Override
    public void onDestroy() {
        tokenTracker.stopTracking();
        profileTracker.stopTracking();
        super.onDestroy();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == RC_SIGN_IN) {
            GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
            handleSignInResult(result);
        }
        mcallbackManager.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
      }

    private static final int RC_SIGN_IN = 007;

    private void signIn() {
        Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
        startActivityForResult(signInIntent, RC_SIGN_IN);
    }

    private void signOut() {
        Auth.GoogleSignInApi.signOut(mGoogleApiClient).setResultCallback(new ResultCallback<Status>() {
            @Override
            public void onResult(@NonNull Status status) {
                updateUI(false);
            }
        });
    }

    private void revokeAccess() {
        Auth.GoogleSignInApi.revokeAccess(mGoogleApiClient).setResultCallback(new ResultCallback<Status>() {
            @Override
            public void onResult(@NonNull Status status) {
                updateUI(false);
            }
        });
    }

    private void handleSignInResult(GoogleSignInResult result) {
        if (result.isSuccess()) {
            //Signed in successfully
            (new SessionManager(LoginActivity.this)).setLogin(true);
            GoogleSignInAccount acct = result.getSignInAccount();
            String personName = acct.getDisplayName();
            String email = acct.getEmail();
            mText.setText("Welcome " + personName + "  " + email + "  buddy!!");
            Picasso.with(this).load(acct.getPhotoUrl()).into(profile_pic);
            updateUI(true);
        } else {
            updateUI(false);
        }
    }

    public void onClick(View v) {
        int id = v.getId();
        switch (id) {
            case R.id.google_login_button:
                signIn();
                break;
            case R.id.btn_sign_out:
                signOut();
                break;
            case R.id.btn_revoke_access:
                revokeAccess();
                break;
        }
    }

    @Override
    public void onStart() {
        super.onStart();
        OptionalPendingResult<GoogleSignInResult> opr = Auth.GoogleSignInApi.silentSignIn(mGoogleApiClient);
        if (opr.isDone()) {
            // If the user's cached credentials are valid, the OptionalPendingResult will be "done"
            // and the GoogleSignInResult will be available instantly.
            GoogleSignInResult result = opr.get();
            handleSignInResult(result);
        } else {
            // If the user has not previously signed in on this device or the sign-in has expired,
            // this asynchronous branch will attempt to sign in the user silently.  Cross-device
            // single sign-on will occur in this branch.
            showProgressDialog();
            opr.setResultCallback(new ResultCallback<GoogleSignInResult>() {
                @Override
                public void onResult(GoogleSignInResult googleSignInResult) {
                    hideProgressDialog();
                    handleSignInResult(googleSignInResult);
                }
            });
        }
    }

    private void showProgressDialog() {
        if (mProgressDialog == null) {
            mProgressDialog = new ProgressDialog(this);
            mProgressDialog.setMessage("Loading");
            mProgressDialog.setIndeterminate(true);
        }

        mProgressDialog.show();
    }

    private void hideProgressDialog() {
        if (mProgressDialog != null && mProgressDialog.isShowing()) {
            mProgressDialog.hide();
        }
    }

    private void updateUI(boolean isSignedIn) {
        if (isSignedIn) {
            googleLoginButton.setVisibility(View.GONE);
            btnSignOut.setVisibility(View.VISIBLE);
            fbLoginButton.setVisibility(View.GONE);
            btnSignOut.setEnabled(true);
            btnRevokeAccess.setEnabled(true);
            googleLoginButton.setEnabled(false);
            btnRevokeAccess.setVisibility(View.VISIBLE);
             } else {
            googleLoginButton.setVisibility(View.VISIBLE);
            fbLoginButton.setVisibility(View.VISIBLE);
            btnSignOut.setVisibility(View.GONE);
            btnSignOut.setEnabled(false);
            btnRevokeAccess.setEnabled(false);
            googleLoginButton.setEnabled(true);
            btnRevokeAccess.setVisibility(View.GONE);
            mText.setText("Hello Buddy Log in to know your name!!");
            profile_pic.setImageResource(R.drawable.common_full_open_on_phone);

        }
    }

    private CallbackManager mcallbackManager;
    private FacebookCallback<LoginResult> callback = new FacebookCallback<LoginResult>() {
        @Override
        public void onSuccess(LoginResult loginResult) {
            (new SessionManager(LoginActivity.this)).setLogin(true);
            AccessToken accessToken = loginResult.getAccessToken();
            Profile profile = Profile.getCurrentProfile();
            if (profile != null) {
                // googleLoginButton.setVisibility(View.INVISIBLE);
                mText.setText("Welcome " + profile.getName() + " buddy!!");
                Picasso.with(LoginActivity.this).load(profile.getProfilePictureUri(50, 50)).into(profile_pic);
                //"https://graph.facebook.com/" +profile.getId() + "/picture?type=large"
            }
        }

        @Override
        public void onCancel() {

            Snackbar.make(findViewById(R.id.rel_layout), "Login Attempt Cancelled!", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();

        }

        @Override
        public void onError(FacebookException error) {
            Snackbar.make(findViewById(R.id.rel_layout), error.getMessage().toString(), Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
        }
    };
    @Override
    protected void onResume() {
        super.onResume();
        Profile profile=Profile.getCurrentProfile();
        if(profile!=null)
            displayWelcomeMessage(1);
       result1=Auth.GoogleSignInApi.getSignInResultFromIntent(new Intent());
    }
    private void displayWelcomeMessage(int i){
        mText.setText("Hello "+Profile.getCurrentProfile().getName());

    }
}

Solution

you can use AccessTokenTracker. you have to listen for a change to a null token. Meaning the user logged out as they click on logout

tokenTracker = new AccessTokenTracker() {
        @Override
        protected void onCurrentAccessTokenChanged(AccessToken oldAccessToken, AccessToken currentAccessToken) {
            if (currentAccessToken == null) {
                    Log.d("FB", "User Logged Out.");
                    //Do your task here after logout
                }
        }
    };
       tokenTracker.startTracking();

You can also use custom Button to log out user and use your method there.. Just hide the view of the loginButton and listen for custom_logout button onClick

custom_logout.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View view) {
            LoginManager.getInstance().logOut();
            //Do your task
        }
    });


Answered By - rafsanahmad007
Answer Checked By - Marie Seifert (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing