Firebase Android自动登录 [英] Firebase Android Auto Login
问题描述
所以我设置了电子邮件/密码注册和登录.
So I setup email/password register and login.
那很好.我以为Firebase会解决这个问题,但显然没有. 我希望在用户关闭应用程序后,下次打开应用程序时已经登录.
That is working. I thought Firebase took care of this but apparently not. I want, after the user closes the app, to be logged in already next time they open the app.
缺少什么?
class LoginActivity : AppCompatActivity(){
lateinit var auth: FirebaseAuth
lateinit var user: FirebaseAuth
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_login)
auth = FirebaseAuth.getInstance()
}
fun loginLoginClicked(view: View) {
// Perform login
val email = loginEmailTxt.text.toString()
val password = loginPasswordTxt.text.toString()
auth.signInWithEmailAndPassword(email, password)
.addOnSuccessListener {
finish()
}
.addOnFailureListener { exception ->
Log.e("Exception", "Could not sign in user - ${exception.localizedMessage}")
}
val loginIntent = Intent(this, MainActivity::class.java)
startActivity(loginIntent)
}
fun loginCreateClicked(view: View) {
// segue to the create user activity
val createIntent = Intent(this, SignUpActivity::class.java)
startActivity(createIntent)
}}
}
推荐答案
Firebase身份验证会自动记住身份验证状态,因此在重新启动应用程序时仍将对用户进行身份验证.
Firebase Authentication does automatically remember authentication state, so the user will still be authenticated when the app is restarted.
但是,如果您的LoginActivity
是启动器活动,那么您仍将进入该活动,因此您需要检查用户是否在onCreate()
中通过了身份验证,然后将其重定向到您的MainActivity
如果他们已经登录,则类似:
However, if your LoginActivity
is the launcher activity, you'll still land on this activity, so you'll need to check whether the user is authenticated in onCreate()
, and then redirect them to your MainActivity
if they are already logged in, something like:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
auth = FirebaseAuth.getInstance();
if (auth.getCurrentUser() != null) {
// User is signed in (getCurrentUser() will be null if not signed in)
val intent = Intent(this, MainActivity::class.java);
startActivity(intent);
finish();
}
}
这利用了 FirebaseUser
对象(如果用户已登录),或者null
(如果他们尚未登录).
This makes use of the FirebaseAuth#getCurrentUser()
method that will return a FirebaseUser
object if the user is logged in, or null
if they are not logged in.
或者,您也可以交换它,以使MainActivity
是启动程序活动,然后仅在用户未登录时才显示LoginActivity
.
Alternatively, you could swap it around so that the MainActivity
is the launcher activity and then only show your LoginActivity
if the user is not logged in.
....
这篇关于Firebase Android自动登录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!