Search code examples
javaandroidgoogle-signinfacebook-sdk-4.0

How to signout a user from the app in android


I'm new to android and now I'm working on making users to login using their facebook and gmail things going well but i need to know how do make the user to signout from the app and login in the user with new accounts. i tried a lot of tutorials but none of them are not as i thought and expected. The user when clicks on logout button from another activity and comebacks to login activity.

example: when user logins from UserAction.class the logout button is in ProfileFragment.class

I tried a lot but haven't found any solution any help.

Code i Tried

public class  UserAction extends AppCompatActivity {

    private CallbackManager callbackManager;
    public LoginButton loginButton;
    private static final String EMAIL = "email";

    private SignInButton signInButton;
    GoogleSignInClient mGoogleSignInClient;
    private FirebaseAuth mAuth;
    private int RC_SIGN_IN = 1;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_action);
        this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

        signInButton = findViewById(R.id.gmail_login_button);
        mAuth = FirebaseAuth.getInstance();

        GoogleSignInOptions gsp = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                .requestIdToken(getString(R.string.default_web_client_id))
                .requestEmail()
                .build();
        mGoogleSignInClient = GoogleSignIn.getClient(this, gsp);

        signInButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                GmailLogin();
            }

            private void GmailLogin() {

                Intent mailSignIn = mGoogleSignInClient.getSignInIntent();
                startActivityForResult(mailSignIn,RC_SIGN_IN);
            }
        });


        AccessToken accessToken = AccessToken.getCurrentAccessToken();
        boolean isLoggedIn = accessToken != null && !accessToken.isExpired();


        AppEventsLogger.activateApp(getApplication());
        callbackManager = CallbackManager.Factory.create();

        loginButton = (LoginButton) findViewById(R.id.fb_login_button);
        loginButton.setReadPermissions(Arrays.asList(EMAIL));

        loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
            @Override
            public void onSuccess(LoginResult loginResult) {

                Intent intent = new Intent(UserAction.this, AppMain.class);
                startActivity(intent);
            }

            @Override
            public void onCancel() {
                // App code
            }

            @Override
            public void onError(FacebookException exception) {
                // App code
            }
        });

    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        callbackManager.onActivityResult(requestCode, resultCode, data);

        if (requestCode == RC_SIGN_IN){

            Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
            handleSignInResult(task);
        }
        super.onActivityResult(requestCode, resultCode, data);

    }

    private void handleSignInResult(Task<GoogleSignInAccount> CompletedTask) {

        try {

            GoogleSignInAccount account = CompletedTask.getResult(ApiException.class);
            Toast.makeText(this, "Signed in Successfully", Toast.LENGTH_SHORT).show();
            FirebaseGoogleAuth(Objects.requireNonNull(account));

        } catch (ApiException e) {

            ConstraintLayout UserAction = findViewById(R.id.userAction);
            Snackbar snackbar = Snackbar.make(UserAction,"Login Failed Please try Again.", Snackbar.LENGTH_SHORT);
            snackbar.show();
            FirebaseGoogleAuth(null);
        }
    }

    private void FirebaseGoogleAuth(final GoogleSignInAccount account) {

        AuthCredential authCredential = GoogleAuthProvider.getCredential(account.getIdToken(), null);
        mAuth.signInWithCredential(authCredential).addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
            @Override
            public void onComplete(@NonNull Task<AuthResult> task) {
                if (task.isSuccessful()){

                    FirebaseUser user = mAuth.getCurrentUser();
                    GoogleSignInAccount googleSignInAccount = GoogleSignIn.getLastSignedInAccount(getApplicationContext());

                    String personName = Objects.requireNonNull(googleSignInAccount).getDisplayName();
                    String personEmail = googleSignInAccount.getEmail();
                    String personId = googleSignInAccount.getId();

                    Toast.makeText(UserAction.this, personName+ "\n" +personEmail + "\n" + personId , Toast.LENGTH_SHORT).show();

                }
            }
        });
    }

}

Solution

  • To sign out from Firebase use

    mAuth.signOut();
    

    And to sign out from google client use

    mGoogleSignInClient.signOut()