本文介绍了如何在Kotlin中使FirebaseAuth.AuthStateListener工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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起作用!

I checked I got something authentication number from firebaseAuth.signInWithEmailAndPassword code line.But my question is about the property FirebaseAuth.AuthStateListener, which doesn't work. When I get authentication number and then I want the AuthStateListener to work!

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

I read the Firebase API, but it didn't work. How can I make FirebaseAuth.AuthStateListener work?

推荐答案

您需要使用监听器调用addAuthStateListener才能使其正常工作.

You need to call addAuthStateListener with your listener in order for it to work.

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

So for example in the onStart of your activity:

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

我建议研究此答案(更多):

I recommend studying this answer (more): Android Studio (Kotlin) - User has to log back into app every time app is closed

这篇关于如何在Kotlin中使FirebaseAuth.AuthStateListener工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-31 18:49