android - 使用 Kotlin 和 Firebase 触发带有 onAuthStateChanged 回调的 sendEmailVerification

标签 android firebase firebase-authentication listener kotlin

我正在开始一个新的 Android 项目,并决定在其中使用 KotlinFirebase,现在我可以使用 createUserWithEmailAndPassword< 成功创建用户 在我的 SignupActivity 上,当 createUserWithEmailAndPassword 完成时,我的用户已成功登录。

现在我正尝试使用在 FirebaseAuth.AuthStateListener 上触发的回调事件进一步获取它使用 onAuthStateChanged(FirebaseAuth auth) 但是我在 onCreate(savedInstanceState: Bundle?) 函数中创建的监听器没有被触发,我缺乏转换 Java 的经验Kotlin 代码无法帮助我找出根本问题。

我有一些基于 Java 的示例代码,如下所示:

Java 示例

onCreate(...//
mAuthListener = new FirebaseAuth.AuthStateListener() {
    @Override
    public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
        FirebaseUser user = firebaseAuth.getCurrentUser();
        if (user != null) {
            // User is signed in
            // NOTE: this Activity should get onpen only when the user is not signed in, otherwise
            // the user will receive another verification email.
            sendVerificationEmail();
        } else {
            // User is signed out

        }
        // ...
    }
};

我的 Kotlin 代码

    FirebaseAuth.AuthStateListener { auth ->
        val user = auth.currentUser
        if(user != null){
            // User is signed in
            Log.d(TAG, "Signed in")
            Toast.makeText(this, "User", Toast.LENGTH_LONG).show();
            sendVerificationEmail()
        }else{
            // User is signed out
            Log.d(TAG, "Signed out")
            Toast.makeText(this, "Null", Toast.LENGTH_LONG).show();
        }
    }

我出于调试目的放置了一些日志和 toast 元素,但它们都没有被触发,我认为 FirebaseAuth.AuthStateListener 中缺少 onAuthStateChanged 但是我不知道如何修复它。

如果有人能就我做错了什么给我一些建议,我将不胜感激。

提前致谢。

最佳答案

这对我有帮助,调用 addAuthStateListener 时请注意括号 - 作为 kotlin 的新手,我使用了 { } curl 的:

    public override fun onStart() {
      super.onStart()
      firebaseAuth.addAuthStateListener(authStateListener)
    }

    public override fun onPause() {
       super.onPause()
       firebaseAuth.removeAuthStateListener(authStateListener)
    }

关于android - 使用 Kotlin 和 Firebase 触发带有 onAuthStateChanged 回调的 sendEmailVerification,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45071788/

相关文章:

android - DebugView 中来自 Firebase Analytics 的用户属性

Java Firebase 按子值搜索

javascript - Firebase 身份验证登录,但成功登录后重定向到主页失败(服务器响应 200)

android - 使用 firebase auth 的 Flutter 应用程序中出现 Google Sign_in_failed 错误

android - 具有多个参数的 LiveData Transformations.map()

带有嵌套键的 Firebase orderByChild()

android - Firebase SignUp 总是报错

android - React-Native: "FirebaseError: No Firebase App ' [默认 ]' has been created - call Firebase App.initializeApp() (app/no-app)"

Android:Horizo​​ntalScrollView smoothScroll 动画时间

android - mpAndroidChart java.lang.NegativeArraySizeException : -46 for Kotlin