简体   繁体   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?

I'm having some issues implementing a custom dialog class getting the response from facebook and passing it back to the main activity.我在实现自定义对话框类从 facebook 获取响应并将其传递回主要活动时遇到了一些问题。

Here there's my custom class:这是我的自定义类:

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?)

}

} }

In my main activity:在我的主要活动中:

   // 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

However it doesn't work: even with debugger I can absolulutely tell nothing can pass through the interface to the activity, nor the "on success" response (as the other ones) is triggered.但是它不起作用:即使使用调试器,我也绝对可以告诉没有任何东西可以通过接口传递到活动,也不会触发“成功”响应(与其他响应一样)。

What can I do to implent it rightly?我能做些什么来正确地实施它?

I solved the issue and I hope this experience can save someone else some precious time :)我解决了这个问题,我希望这个经验可以为其他人节省一些宝贵的时间:)

  1. listener needs to be correctly initialized into the custom class, where "c" is the Activity passed from my main activity: listener 需要正确初始化到自定义类中,其中“c”是从我的主要活动传递的活动:

     //in onCreate, inside the custom dialog class: listener = c as LoginDialog.LoginListener
  2. since the callback needs time to come back, it's useless to pass the response to the main activity: instead is better to pass the pushed button由于回调需要时间返回,因此将响应传递给主活动是没有用的:相反,传递按下的按钮更好

     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. in main activity let's set it up to wait for the result: here is the listener在主要活动中,让我们将其设置为等待结果:这是侦听器

     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 }

Now the onActivityResult method can work properly现在 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)}

The same, now, for the firebase auth initializated in onCreate现在,对于在 onCreate 中初始化的 Firebase 身份验证也是如此

    //firebase auth in onCreate
    auth = Firebase.auth

and updated here (see the official firebase doc for this)并在此处更新(有关此信息,请参阅官方 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)
            }

            // ...
        }
}
    

Hope it helps!希望能帮助到你!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在 Flutter 中设置 firebase 身份验证(分别使用 ``twitter_login: ^4.0.1`` 和 ``flutter_facebook_auth: ^4.0.1```)? - How to set up firebase Authentication (with ```twitter_login: ^4.0.1``` and ```flutter_facebook_auth: ^4.0.1``` respectively) in Flutter? 如何在Android的自定义对话框中设置自定义侦听器? - How to set up a custom listener in a custom dialog for android? 如何配置 Firebase Auth 对话框的超链接 - How to configue hyperlink of Firebase Auth's Dialog 如何为自定义对话框设置按钮单击侦听器? - How to set button click listener for Custom Dialog? 如何在接口中指定回调/侦听器 - How to specify a callback/listener in an interface 带有 Firebase 身份验证的空指针。 如何将监听器放到另一个类 - Null pointer with Firebase auth. How to put listener to another class 如何在存储库 class MVVM 中使用 Firebase 身份验证侦听器? - How to use a Firebase auth listener in a repository class MVVM? 如何在mainActivity而非自定义视图中为gridview单选按钮设置onclick侦听器 - How to set onclick listener for gridview radio buttons in mainactivity instead custom view 如何将onclick处理程序传递给自定义对话框类 - how to pass an onclick handler to a custom dialog class Facebook登录成功,但firebase身份验证抛出异常 - Facebook login successful but firebase auth throw exception
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM