skip to Main Content

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


  1. 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:

    FirebaseUser currentUser = FirebaseAuth.getInstance().getCurrentUser();
    if (Objects.nonNull(currentUser)) {
        // This means that user has already logged into the app once.
        // So you can redirect to MainActivity.java
    
        startActivity(new Intent(this, MainActivity.class));
    } else {
        // This means no user logged into the app before.
        // So you can redirect to LoginActivity.java
    
        startActivity(new Intent(this, LoginActivity.class));
    }
    

    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.

    Login or Signup to reply.
  2. I want to keep the user logged in.

    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:

    One time login in app – FirebaseAuth

    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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search