Android Studio (kotlin) - User Has To Log Back Into App Every Time App Is Closed
Solution 1:
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:
val authStateListener = FirebaseAuth.AuthStateListener { firebaseAuth ->
val firebaseUser = firebaseAuth.currentUser
if (firebaseUser != null) {
val intent = Intent(this, MainActivity::class.java)
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:
valfirebaseAuth= FirebaseAuth.getInstance()
And start listening for changes in your onStart()
method like this:
overridefunonStart() {
super.onStart()
firebaseAuth!!.addAuthStateListener(this.authStateListener!!)
}
In the MainActivity
, you should do the same thing:
val authStateListener = FirebaseAuth.AuthStateListener { firebaseAuth ->
val firebaseUser = firebaseAuth.currentUser
if (firebaseUser == null) {
val intent = Intent(this, LoginActivity::class.java)
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:
overridefunonStop() {
super.onStop()
firebaseAuth!!.removeAuthStateListener(this.authStateListener!!)
}
Solution 2:
I have developer a similar app and I simply use a splash screen that checks if the users is logged or not and then open the right screen. The splash doesn't need to be to complex: in fact you can even avoid to set a view and just check whatever you want. This article explains it very clearly.
Remember to call finish() on the splash activity after launching the right one.
Post a Comment for "Android Studio (kotlin) - User Has To Log Back Into App Every Time App Is Closed"