You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android Studio开发应用:Play Store下载后Firebase Google认证失效

问题:Play Store发布版Google认证失效,本地测试正常

我开发的时间管理应用Mission Control已实现邮箱密码认证,新增基于Firebase的Google认证功能后,Android Studio本地调试时Google注册/登录完全正常,但上传至Play Store下载使用时功能失效:点击Google按钮能弹出已有邮箱列表,选择后无任何注册/登录动作,也无错误提示,多部手机测试均出现此问题。

应用包名:com.missioncontrol.timeplanning

相关代码如下:

private fun initSignInWithGoogle() //Called from onCreate
{
    //Actions for signing in w google:

    //Sign w Google btn
    val btnSignWGoogle = binding?.btnSignWGoogle

    // Initialize sign in options the client-id is copied form Firebase auth
    val googleSignInOptions = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
        .requestIdToken("/*Here is the id*/")
        .requestEmail()
        .build()

    // Initialize sign in client
    googleSignInClient = GoogleSignIn.getClient(this@IntroActivity, googleSignInOptions)

    btnSignWGoogle?.setOnClickListener { // Initialize sign in intent
        val intent: Intent = googleSignInClient.signInIntent
        // Start activity for result
        startActivityForResult(intent, Constants.GOOGLE_SIGN_REQUEST_CODE) //Show emails
    }
}

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

    // Check whether we returned from email selection and an email was selected
    if (requestCode == Constants.GOOGLE_SIGN_REQUEST_CODE&&resultCode == RESULT_OK) {
        // When request code is equal to GOOGLE_SIGN_REQUEST_CODE
         signInAccountTask =
            GoogleSignIn.getSignedInAccountFromIntent(data)

        //Get the user data
         googleSignInAccount = signInAccountTask.result
         displayName = googleSignInAccount?.displayName!!
         email = googleSignInAccount?.email!!
         photoUrl = googleSignInAccount?.photoUrl?.toString()!!


        Log.d("SignInGoogle", "Display Name: $displayName")
        Log.d("SignInGoogle", "Email: $email")
        Log.d("SignInGoogle", "Photo URL: $photoUrl")


        //Checks if the email is in the USERS collection
        FireStoreClass().checkEmailUniqueness(email!!, this) { isUnique ->
        }
    }
    else{
        Log.d("SignInGoogle", "Error + " + requestCode.toString())
    }
}

fun isEmailUnique(isUnique: Boolean)
{
    //Called from firebase
    if (isUnique) {
        Log.d("SignInGoogle", "Email unique")
        //Email is not used - create new user and go to trailer
        try {
            try {              
                if (googleSignInAccount != null) {
                    // When sign in account is not equal to null initialize auth credential
                    val authCredential: AuthCredential = GoogleAuthProvider.getCredential(
                        googleSignInAccount.idToken, null
                    )
                    // Check credential and sign the user up
                    auth.signInWithCredential(authCredential)
                        .addOnCompleteListener(this) { task ->
                            // Check sign up
                            if (task.isSuccessful) {
                                // When task is successful redirect
                                Log.d("SignInGoogle", "Trying to add user to collection")
                                val user = com.missioncontrol.timeplanning.models.User("", displayName!!,email!!,photoUrl?:"",0,"",)
                                FireStoreClass().registerUser(this, user)
                                // Display Toast
                                displayToast("Thank you for registering")
                            } else {
                                // When task is unsuccessful display Toast
                                displayToast(
                                    "Authentication Failed :" + task.exception?.message
                                )
                            }
                        }
                }
            } catch (e: ApiException) {
                e.printStackTrace()
                Log.d("SignInGoogle", e.toString())
            }

        }
        catch (e: Exception)
        {
            Toast.makeText(this@IntroActivity, "Error please try again or contact support", Toast.LENGTH_SHORT).show()
        }

    }
    else
    {//Email exists - sign in
        Log.d("SignInGoogle", "Email not unique")

        if (signInAccountTask.isSuccessful) {
            Log.d("SignInGoogle", "Success sign in")
            // When google sign in successful initialize string
            val s = "Google sign in successful"
            // Display Toast
            displayToast(s)
            // Initialize sign in account
            try {
                // Initialize sign in account
                if (googleSignInAccount != null) {
                    // When sign in account is not equal to null initialize auth credential
                    val authCredential: AuthCredential = GoogleAuthProvider.getCredential(
                        googleSignInAccount.idToken, null
                    )
                    // Check credential
                    auth.signInWithCredential(authCredential)
                        .addOnCompleteListener(this) { task ->
                            // Check condition
                            if (task.isSuccessful) {
                                // When task is successful redirect to Main activity
                                startActivity(
                                    Intent(
                                        this@IntroActivity,
                                        MainActivity::class.java
                                    ).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                                )
                            } else {
                                // When task is unsuccessful display Toast
                                displayToast(
                                    "Authentication Failed :" + task.exception?.message
                                )
                            }
                        }
                }
            } catch (e: ApiException) {
                e.printStackTrace()
                Log.d("SignInGoogle", e.toString())
            }
        }
        else
        {
            Log.d("SignInGoogle", signInAccountTask.toString())
        }
    }
}

fun userRegisteredSuccess() //Gets called automatically from FireStoreClass upon registration
{
    //User was added to collection successfully - go to trailer
    Log.d("SignInGoogle", "added user to collection")

    Toast.makeText(this, "Thanks for registering" +
            "." , Toast.LENGTH_LONG).show()
    hideProgressDialog()

                startActivity(Intent(this, TrailerActivity::class.java))
                finish()
}

排查与解决方法

1. 修复回调空实现(核心问题)

你的onActivityResult中调用FireStoreClass().checkEmailUniqueness时,回调函数是空的:

FireStoreClass().checkEmailUniqueness(email!!, this) { isUnique ->
}

这会导致后续的isEmailUnique方法根本不会被执行,选择邮箱后自然没有任何动作。修改为:

FireStoreClass().checkEmailUniqueness(email!!, this) { isUnique ->
    isEmailUnique(isUnique)
}

2. 处理Google登录异步任务的异常

直接调用signInAccountTask.result会在任务失败时抛出未捕获异常,导致流程中断。改用异步回调处理:

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    super.onActivityResult(requestCode, resultCode, data)
    if (requestCode == Constants.GOOGLE_SIGN_REQUEST_CODE && resultCode == RESULT_OK) {
        val signInAccountTask = GoogleSignIn.getSignedInAccountFromIntent(data)
        signInAccountTask.addOnCompleteListener { task ->
            if (task.isSuccessful) {
                val googleSignInAccount = task.result ?: run {
                    displayToast("获取账号信息失败")
                    return@addOnCompleteListener
                }
                displayName = googleSignInAccount.displayName!!
                email = googleSignInAccount.email!!
                photoUrl = googleSignInAccount.photoUrl?.toString() ?: ""
                FireStoreClass().checkEmailUniqueness(email!!, this) { isUnique ->
                    isEmailUnique(isUnique)
                }
            } else {
                val exception = task.exception
                if (exception is ApiException) {
                    Log.e("SignInGoogle", "登录错误码: ${exception.statusCode}")
                    displayToast("登录失败:${exception.message}")
                } else {
                    Log.e("SignInGoogle", "登录失败: ${exception?.message}")
                    displayToast("登录失败,请重试")
                }
            }
        }
    } else {
        Log.d("SignInGoogle", "请求异常,请求码: $requestCode")
    }
}

3. 配置Play App Signing对应的SHA-1和OAuth客户端ID

Play Store发布的应用会使用Google提供的签名证书,和本地调试的SHA-1不一致,导致Firebase认证失败:

  • 登录Play Console,进入你的应用 -> 应用签名,复制应用签名证书的SHA-1
  • 登录Firebase控制台,进入你的项目 -> 项目设置 -> 应用,添加上述SHA-1
  • 进入Google Cloud控制台,找到项目的API和服务 -> 凭据,创建新的Android OAuth客户端ID,输入包名和Play签名的SHA-1
  • 将新生成的客户端ID替换到代码中requestIdToken("/*Here is the id*/")的位置

4. 检查Firebase与Play Store配置

  • 确保Firebase控制台中已启用Google登录方式
  • 确认应用已添加INTERNET权限(发布版本可能被ProGuard移除,需在Manifest中明确声明)
  • 检查ProGuard规则,确保Google Sign-In和Firebase的相关类未被混淆:
    -keep class com.google.android.gms.auth.api.signin.** { *; }
    -keep class com.google.firebase.auth.** { *; }
    

内容的提问来源于stack exchange,提问作者Itay Tamir

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.29 23:27:32