I am trying to make an app with a login function and I want to keep the user logged in.
I’m using Firebase auth and android studio.
This is what I tried:
auth.signInWithEmailAndPassword(txt_email, txt_password)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()){
Intent intent = new Intent(login.this, sendForm.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish();
}
else {
Toast.makeText(login.this, "cant sing in", Toast.LENGTH_SHORT).show();
}
}
});
2
Answers
First you need to check if the user exists when you log in to the app from second time. If the user exists you directly take him to the MainActivity else you’ll take him to the LoginActivity.
So, your launchActivity should be something that is other then Login/Main activities. Typically, it would be a splash screen. So, let’s say you’re launch activity is SplashActivity.
Now, in your SplashActivity.java onCreate() do this:
If you don’t want to use a SplashScreen, you can check for the user existence in LoginActivity.java using
FirebaseUser currentUser = FirebaseAuth.getInstance().getCurrentUser();
and redirect him to MainActivity if currentUser is nonNull.This is happening by default. There is nothing special that you need to do in order to keep your users logged in. They will be logged in until they explicitly sign out. Here is the official documentation for Android:
If you want to keep track of the auth state, then please check my answer from the following post:
Besides that, please also note that the state of being "signed in" doesn’t depend on internet connectivity but on the user token currently in use, which is present locally and has not expired after one hour since the last refresh.