簡體   English   中英

使用Kotlin和Firebase通過onAuthStateChanged回調觸發sendEmailVerification

[英]Using Kotlin and Firebase to trigger a sendEmailVerification with onAuthStateChanged callback

我正在開始一個新的Android項目並決定使用KotlinFirebase ,現在我能夠在我的SignupActivity上使用createUserWithEmailAndPassword成功創建用戶,並且當createUserWithEmailAndPassword完成時我的用戶已成功登錄。

現在我正在嘗試使用onAuthStateChanged(FirebaseAuth auth)FirebaseAuth.AuthStateListener上觸發的回調事件來進一步使用,但是我在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();
        }
    }

我把一些日志和烤面包元素用於調試目的,但都沒有得到被觸發,我想的是, onAuthStateChanged缺少FirebaseAuth.AuthStateListener內,但我不知道如何解決它。

如果有人能給我一些關於我做錯的建議,那將非常感激。

提前致謝。

這對我有所幫助,在調用addAuthStateListener時注意括號 - 對kotlin來說是新用的我使用了{ }卷曲的:

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM