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();
}
// ...
}
});
}
}
Use this code FirebaseAuth.getInstance().signOut();