One time login in app - FirebaseAuth
The simplest way to achieve this is to use a listener. Let's assume you have two activities, the LoginActivity
and the MainActivity
. The listener that can be created in the LoginActivity
should look like this:
FirebaseAuth.AuthStateListener authStateListener = new FirebaseAuth.AuthStateListener() {
@Override
public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
FirebaseUser firebaseUser = firebaseAuth.getCurrentUser();
if (firebaseUser != null) {
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
startActivity(intent);
finish();
}
}
};
This basically means that if the user is logged in, skip the LoginActivity
and go to the MainActivity
.
Instantiate the FirebaseAuth
object:
FirebaseAuth firebaseAuth = FirebaseAuth.getInstance();
And start listening for changes in your onStart()
method like this:
@Override
protected void onStart() {
super.onStart();
firebaseAuth.addAuthStateListener(authStateListener);
}
In the MainActivity
, you should do the same thing:
FirebaseAuth.AuthStateListener authStateListener = new FirebaseAuth.AuthStateListener() {
@Override
public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
FirebaseUser firebaseUser = firebaseAuth.getCurrentUser();
if (firebaseUser == null) {
Intent intent = new Intent(MainActivity.this, LoginActivity.class);
startActivity(intent);
}
}
};
Which basically means that if the user is not logged in, skip the MainActivity
and go to the LoginActivity
. In this activity you should do the same thing as in the LoginActivity
, you should start listening for changes in the onStart()
.
In both activities, don't forget to remove the listener in the moment in which is not needed anymore. So add the following line of code in your onStop()
method:
@Override
protected void onStop() {
super.onStop();
firebaseAuth.removeAuthStateListener(authStateListener);
}
You can save user login session in shared Preference
Do this when your login got Login Success
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", Activity.MODE_PRIVATE);
Editor editor = pref.edit();
editor.putBoolean("key_name", true); // Storing boolean - true/false
editor.commit();
and When Your apps is Starts (like Splash or login Page) use this
SharedPreferences sp=this.getSharedPreferences("MyPref", Context.MODE_PRIVATE);
boolean b = sp.getBoolean("key_name", false);
if(b==true){
//User Already Logged in skip login page and continue to next process
}else{
//User is Not logged in, show login Form
}
It will works for you.