簡體   English   中英

如何在自定義 Dialog 類中設置接口和偵聽器以將 Facebook 的登錄回調傳遞給 MainActivity 中的 firebase auth?

[英]How to set up Interface and listener in custom Dialog class to pass Facebook's login callback to firebase auth in MainActivity?

我在實現自定義對話框類從 facebook 獲取響應並將其傳遞回主要活動時遇到了一些問題。

這是我的自定義類:

class LoginDialog(var c: Activity) : Dialog(c), View.OnClickListener {

val mContext = c
private lateinit var realFbButton: LoginButton
private lateinit var listener: LoginListener

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    requestWindowFeature(Window.FEATURE_NO_TITLE)
    getWindow()?.setBackgroundDrawableResource(android.R.color.transparent);
    setContentView(R.layout.login_dialog)

    // here image to cover the real facebook LoginButton
    val loginFbButton: ImageView = findViewById(R.id.facebookButton)
    loginFbButton.setOnClickListener(this)

    // the real facebook login button I wanna click to start the facebook auth process
    realFbButton = findViewById(R.id.facebooOfficalButton)
    realFbButton.setOnClickListener(this)

}

override fun onClick(v: View) {
    when (v.id) {
        R.id.facebookButton -> {realFbButton.performClick()
            // Initialize Facebook Login button
            //TODO: (nothing necessary)
        }
        R.id.facebooOfficalButton -> {
            realFbButton.setReadPermissions("email", "public_profile")

            // register callback after LoginButton has been pushed
            realFbButton.registerCallback(callbackManager, object :
                FacebookCallback<LoginResult>{
                override fun onSuccess(result: LoginResult?) {
                    try{
                        Toast.makeText(context, "success", Toast.LENGTH_LONG).show()
                        // listener to pass result
                        listener.passLoginListener(result)
                    }
                    catch(e: Exception){
                        Toast.makeText(context, "exception" + e, Toast.LENGTH_LONG).show()

                    }
                    TODO("Not yet implemented")
                }

                override fun onCancel() {
                    TODO("Not yet implemented")
                }

                override fun onError(error: FacebookException?) {
                    TODO("Not yet implemented")
                }
            })
        }
        else -> {
            Toast.makeText(mContext, "id not recognized: " + v, Toast.LENGTH_LONG).show()
        }
    }
    dismiss()
}

fun setLoginListener(listener: LoginListener?) {
    this.listener = listener!!
}


interface LoginListener{
    public fun passLoginListener(callBack: LoginResult?)

}

}

在我的主要活動中:

   // interface implementation
   class CentralActivity : AppCompatActivity(), LoginDialog.LoginListener{/* my full class is  here
   ...*/}

   
   override fun passLoginListener(callBack: LoginResult?) {/*here call to handleFacebookAccessToken(token: AccessToken)*/}
  
   // in onCreate overriden method:
   val dialog = LoginDialog(this@CentralActivity)
   dialog.setLoginListener(this@CentralActivity) // this activate the listener

但是它不起作用:即使使用調試器,我也絕對可以告訴沒有任何東西可以通過接口傳遞到活動,也不會觸發“成功”響應(與其他響應一樣)。

我能做些什么來正確地實施它?

我解決了這個問題,我希望這個經驗可以為其他人節省一些寶貴的時間:)

  1. listener 需要正確初始化到自定義類中,其中“c”是從我的主要活動傳遞的活動:

     //in onCreate, inside the custom dialog class: listener = c as LoginDialog.LoginListener
  2. 由於回調需要時間返回,因此將響應傳遞給主活動是沒有用的:相反,傳遞按下的按鈕更好

     override fun onClick(v: View) { when (v.id) { R.id.facebookButton -> {realFbButton.performClick() //TODO: nothing here } R.id.facebooOfficalButton -> { realFbButton.setReadPermissions("email", "public_profile") this.listener.passLoginListener(realFbButton) // here we go passing the button to the interface and to the main activity } else -> { Toast.makeText(mContext, "id not recognized: " + v, Toast.LENGTH_LONG).show() } } dismiss()
  3. 在主要活動中,讓我們將其設置為等待結果:這是偵聽器

     override fun passLoginListener(fbb: LoginButton): LoginButton { // get the LoginButton and set up the receiver fbb.registerCallback(callbackManager, object : FacebookCallback<LoginResult> { override fun onSuccess(result: LoginResult?) { try{ Toast.makeText(applicationContext, "success", Toast.LENGTH_LONG).show() handleFacebookAccessToken(result!!.accessToken) } catch(e: Exception){ Toast.makeText(applicationContext, "exception" + e, Toast.LENGTH_LONG).show() } } override fun onCancel() { TODO("Not yet implemented") } override fun onError(error: FacebookException?) { TODO("Not yet implemented") } }) return fbb }

現在 onActivityResult 方法可以正常工作了

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    super.onActivityResult(requestCode, resultCode, data)

    // Pass the activity result back to the Facebook SDK
    callbackManager.onActivityResult(requestCode, resultCode, data)}

現在,對於在 onCreate 中初始化的 Firebase 身份驗證也是如此

    //firebase auth in onCreate
    auth = Firebase.auth

並在此處更新(有關此信息,請參閱官方 firebase 文檔)

private fun handleFacebookAccessToken(token: AccessToken) {
    Log.d("Tag", "handleFacebookAccessToken:$token")
    Toast.makeText(applicationContext, "in handle fb login " + token, Toast.LENGTH_LONG).show()

    val credential = FacebookAuthProvider.getCredential(token.token)
    auth.signInWithCredential(credential)
        .addOnCompleteListener(this) { task ->
            if (task.isSuccessful) {
                // Sign in success, update UI with the signed-in user's information
                Log.d("Tag", "signInWithCredential:success")
                val user = auth.currentUser
                updateUI(user)
            } else {
                // If sign in fails, display a message to the user.
                Log.w("Tag", "signInWithCredential:failure", task.exception)
                Toast.makeText(baseContext, "Authentication failed.",
                    Toast.LENGTH_SHORT).show()
                updateUI(null)
            }

            // ...
        }
}
    

希望能幫助到你!

暫無
暫無

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

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