class LoginActivity : AppCompatActivity() {

    private val firebaseAuth = FirebaseAuth.getInstance()
    private val firebaseAuthListener = FirebaseAuth.AuthStateListener {
        val user = firebaseAuth.currentUser?.uid
        user?.let {
            startActivity(HomeActivity.newIntent(this))
            finish()
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_login)
        loginProgressLayout.setOnTouchListener { v, event -> true }
    }

    fun onLogin(v: View) {
        var proceed = true
        if (emailET.text.isNullOrEmpty()) {
            emailTIL.error = "email is required"
            emailTIL.isErrorEnabled = true
            proceed = false
        }
        if(passwordET.text.isNullOrEmpty()) {
            passwordTIL.error = "password is required"
            passwordTIL.isErrorEnabled = true
            proceed = false
        }
        if(proceed){
            loginProgressLayout.visibility = View.VISIBLE
            firebaseAuth.signInWithEmailAndPassword(emailET.text.toString(), passwordET.text.toString())
                .addOnCompleteListener { task ->
                    if (!task.isSuccessful){
                        loginProgressLayout.visibility = View.GONE
                        Toast.makeText(this@LoginActivity, "LoginError", Toast.LENGTH_SHORT).show()
                    }
                }
                .addOnFailureListener { exception ->
                    exception.printStackTrace()
                    loginProgressLayout.visibility = View.GONE
                }
        }
    } //onLogin end


我检查了我是否从firebaseAuth.signInWithEmailAndPassword代码行获得了身份验证号码。
但是我的问题是关于属性FirebaseAuth.AuthStateListener,它不起作用。
当我获得验证码后,我希望AuthStateListener工作!

我阅读了Firebase API,但是没有用。如何使FirebaseAuth.AuthStateListener工作?

最佳答案

您需要与您的监听器一起调用addAuthStateListener才能使它起作用。

例如,在您的活动的onStart中:

override fun onStart() {
    super.onStart()
    firebaseAuth!!.addAuthStateListener(this.firebaseAuthListener!!)
}


我建议研究此答案(更多):Android Studio (Kotlin) - User has to log back into app every time app is closed

07-27 19:33