41

I am making a simple authentication app in Android using Firebase authentication. Till now I am successful in signing the user in, however the issue is that the user remains signed in, and I can't find a way to sign him out.

Here is my MainActivity.java code

public class MainActivity extends AppCompatActivity {

    private FirebaseAuth mAuth;
    private FirebaseAuth.AuthStateListener mAuthListener;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //tracking the sign in and singn out operations
        mAuth = FirebaseAuth.getInstance();
        mAuthListener = new FirebaseAuth.AuthStateListener(){
            @Override
            public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
                FirebaseUser user = firebaseAuth.getCurrentUser();
                if (user!=null){
                    System.out.println("User logged in");
                }
                else{
                    System.out.println("User not logged in");
                }
            }
        };
    }


    public void onStart(){
        super.onStart();
        mAuth.addAuthStateListener(mAuthListener);
    }
    public void onStop(){
        super.onStop();
        if (mAuthListener != null) {
            mAuth.removeAuthStateListener(mAuthListener);

        }
    }


    public void buttonClicked(View view){

        EditText editemail = (EditText) findViewById(R.id.email);
        EditText editpass = (EditText) findViewById(R.id.password);

        String email = editemail.getText().toString();
        String password = editpass.getText().toString();


        mAuth.signInWithEmailAndPassword(email, password)
                .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {
                     //   Log.d(TAG, "signInWithEmail:onComplete:" + task.isSuccessful());
                        Toast.makeText(MainActivity.this, "Authentication Success.",
                                Toast.LENGTH_SHORT).show();
                        startActivity(new Intent(MainActivity.this,Success.class));
                        // If sign in fails, display a message to the user. If sign in succeeds
                        // the auth state listener will be notified and logic to handle the
                        // signed in user can be handled in the listener.
                        if (!task.isSuccessful()) {
                           // Log.w(TAG, "signInWithEmail", task.getException());
                            Toast.makeText(MainActivity.this, "Authentication failed.",
                                    Toast.LENGTH_SHORT).show();
                        }

                        // ...
                    }
                });
    }



}
AL.
  • 36,815
  • 10
  • 142
  • 281
Suzan Cruz
  • 501
  • 2
  • 5
  • 9
  • 1
    I think You need to call "unauth()" immediately deletes that token from local storage because when you call firebase authentication it keeps the token for that particular user in local storage on device.In recent time "signOut" took the place of "unauth" and it's look like deprecated. – Abu Sufian Mar 03 '17 at 06:00
  • Thanks @AbuSufian, I placed the "FirebaseAuth.getInstance().signOut();" in onStop method and it works. – Suzan Cruz Mar 03 '17 at 06:06
  • @SuzanCruz Would you mind selecting a "correct answer". There are a few duplicates and your selecting one to be Green would help us not need to read them all. – akauppi Aug 05 '19 at 16:30
  • this might help:https://stackoverflow.com/a/56338259/6738361 – s.dragos Jan 03 '21 at 21:17

13 Answers13

54

Use this code FirebaseAuth.getInstance().signOut();

saurabh dixit
  • 863
  • 6
  • 19
33

You can simply call this

FirebaseAuth.getInstance().signOut();

If you want to perform some action after sign out then use this one.

public void onClick(View v) {
    if (v.getId() == R.id.sign_out) {
        AuthUI.getInstance()
            .signOut(this)
            .addOnCompleteListener(new OnCompleteListener<Void>() {
                public void onComplete(@NonNull Task<Void> task) {
                    // user is now signed out
                    startActivity(new Intent(MyActivity.this, SignInActivity.class));
                    finish();
                }
            });
        }
    }
Md. Monsur Hossain Tonmoy
  • 11,045
  • 2
  • 22
  • 19
  • 2
    in order to add the .addOnCompleteListener for signOut you need to implement Firebase UI like the docs on github states "The entry point to the authentication flow is the com.firebase.ui.auth.AuthUI class." Latest versions here https://github.com/firebase/FirebaseUI-Android/blob/master/auth/README.md#configuration – Gastón Saillén Oct 02 '18 at 18:10
15

This can be solved by using AuthStateListener

//Declaration and defination
private FirebaseAuth firebaseAuth;
FirebaseAuth.AuthStateListener authStateListener = new FirebaseAuth.AuthStateListener() {
    @Override
    public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
        if (firebaseAuth.getCurrentUser() == null){
            //Do anything here which needs to be done after signout is complete
            signOutComplete();
        }
        else {
        }
    }
};

//Init and attach
firebaseAuth = FirebaseAuth.getInstance();
firebaseAuth.addAuthStateListener(authStateListener);

//Call signOut()
firebaseAuth.signOut();

Snippet : https://codepad.co/snippet/aPeehdoD

Yash
  • 3,438
  • 2
  • 17
  • 33
12

Firebase auth is provide signout method.

 FirebaseAuth.getInstance().signOut();
Jd Prajapati
  • 1,953
  • 13
  • 24
  • Thanks, it worked, I put this code FirebaseAuth.getInstance().signOut();" in my onStop method. Hopefully thats the correct way td do so. – Suzan Cruz Mar 03 '17 at 06:04
8

Try This

FirebaseAuth fAuth = FirebaseAuth.getInstance();
 fAuth.signOut();
Anshul Khare
  • 391
  • 1
  • 4
  • 13
6

if you are using firebaseAuthUI then recommended method is

public void onClick(View v) {
if (v.getId() == R.id.sign_out) {
    AuthUI.getInstance()
        .signOut(this)
        .addOnCompleteListener(new OnCompleteListener<Void>() {
            public void onComplete(@NonNull Task<Void> task) {
                // user is now signed out
                startActivity(new Intent(MyActivity.this, SignInActivity.class));
                finish();
            }
        });
    }
}

according to firebaseAuthUI github Guide.

captainchhala
  • 831
  • 1
  • 7
  • 14
3

use this`

findViewById(R.id.signout).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            FirebaseAuth.getInstance().signOut();
            Intent intent = new Intent(currentActivity.this, MainActivity.class);             

intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);//makesure user cant go back
                startActivity(intent);
            }
        });`
griffins
  • 7,079
  • 4
  • 29
  • 54
3
logout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
  firebaseAuth.getInstance().signOut();
  Intent intent = new Intent(SettingsActivity.this,SignInActivity.class);
  startActivity(intent);
  }
});
Saneth
  • 31
  • 2
  • Make sure you add the following before onCreate method: private FirebaseAuth firebaseAuth; private FirebaseUser firebaseUser; – Saneth Aug 31 '20 at 05:38
2

This one just signs you out from the current application .

if you are using a fragment do this

AuthUI.getInstance().signOut(getActivity());

if you are using an activity do this

AuthUI.getInstance().signOut(getApplicationContext);

cheers!

Niamatullah Bakhshi
  • 1,445
  • 16
  • 27
1

For complete log out I would recommend :

mFirebaseAuth.signOut();
Auth.GoogleSignInApi.signOut(mGoogleApiClient);
Phil
  • 305
  • 1
  • 3
  • 13
0

There have several way to sign out user:

1. FirebaseUI: Refarence

Add depenencies:

dependencies {
    implementation 'com.firebaseui:firebase-ui-auth:4.0.0'
}

Then:

public void onClick(View v) {
if (v.getId() == R.id.sign_out) {
    AuthUI.getInstance()
        .signOut(this)
        .addOnCompleteListener(new OnCompleteListener<Void>() {
            public void onComplete(@NonNull Task<Void> task) {
                // user is now signed out
                startActivity(new Intent(MyActivity.this, SignInActivity.class));
                finish();
            }
        });
    }
}

2. Kotlin: Referance

Use Android default Authentication dependency, ex: com.google.firebase:firebase-auth:16.0.1

firebase.auth().signOut().then(function() {
  // Sign-out successful.
}).catch(function(error) {
  // An error happened.
});

3. Default with java:

Use Android default Authentication dependency, ex: com.google.firebase:firebase-auth:16.0.1

FirebaseAuth mAuth = FirebaseAuth.getInstance();
try {
     mAuth.signOut();
     Toast.makeText(this, "User Sign out!", Toast.LENGTH_SHORT).show();
}catch (Exception e) {
     Log.e(TAG, "onClick: Exception "+e.getMessage(),e );
}
Sheikh Hasib
  • 7,423
  • 2
  • 25
  • 37
0
FirebaseAuth.getInstance().signOut();

Then, to detect the sign-in status:

private FirebaseAuth mAuth = FirebaseAuth.getInstance()
public static boolean mAuthSignIn() {
    if (mAuth != null) {
        FirebaseUser user = mAuth.getCurrentUser();
        return user != null;
    }
    return false;
}
-3

Try this one it is working for me.

FirebaseAuth.getInstance()
        .signOut(this)
        .addOnCompleteListener(new OnCompleteListener<Void>() {
            public void onComplete(@NonNull Task<Void> task) {
                // user is now signed out
                startActivity(new Intent(YOUR CURRENT ACTIVITY, ACTIVITY IN WHICH YOU WANT TO MOVE));
                finish();
            }
        });
Mr. Mad
  • 1,230
  • 1
  • 14
  • 28
  • # Khyati Fataniai don't think that you ever tried the above code mentioned in my reply. otherwise you will not say like this . i my self tried this one in my live app which is completely built on firebase . – Mr. Mad Aug 04 '17 at 18:11
  • I have tried your code, but it shows error on signOut method – Khyati Vara Aug 05 '17 at 04:37