英文:
Unable to sign In with google account using Firebase authentication
问题
以下是代码的翻译部分:
package com.turbotechnologies.quizgame
import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.Color
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.TextView
import android.widget.Toast
import androidx.activity.result.ActivityResultCallback
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import com.google.android.gms.auth.api.Auth
import com.google.android.gms.auth.api.signin.GoogleSignIn
import com.google.android.gms.auth.api.signin.GoogleSignInAccount
import com.google.android.gms.auth.api.signin.GoogleSignInClient
import com.google.android.gms.auth.api.signin.GoogleSignInOptions
import com.google.android.gms.common.api.ApiException
import com.google.android.gms.tasks.Task
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.GoogleAuthCredential
import com.google.firebase.auth.GoogleAuthProvider
import com.turbotechnologies.quizgame.R.drawable
import com.turbotechnologies.quizgame.databinding.ActivityLoginBinding
class LoginActivity : AppCompatActivity() {
lateinit var loginBinding: ActivityLoginBinding
private val auth: FirebaseAuth = FirebaseAuth.getInstance()
// 创建一个 Google 登录客户端的对象
lateinit var googleSignInClient: GoogleSignInClient
lateinit var activityResultLauncher: ActivityResultLauncher<Intent>
@SuppressLint("SetTextI18n")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
loginBinding = ActivityLoginBinding.inflate(layoutInflater)
val view = loginBinding.root
setContentView(view)
val textForGoogleSignInButton = loginBinding.buttonGoogleSignIn.getChildAt(0) as TextView
// 更改 Google 登录按钮的文本
textForGoogleSignInButton.text = "使用 Google 登录"
textForGoogleSignInButton.setTextColor(Color.BLACK)
textForGoogleSignInButton.textSize = 18F
textForGoogleSignInButton.setBackgroundResource(drawable.button_shape)
// 注册活动
registeringActivityForGoogleSignIn()
loginBinding.buttonGoogleSignIn.setOnClickListener {
loginBinding.progressBar4.visibility = View.VISIBLE
signInGoogle()
}
}
private fun signInGoogle() {
val gso = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id))
.requestEmail().build()
googleSignInClient = GoogleSignIn.getClient(ths,gso)
signIn()
}
private fun signIn() {
val signInIntent = googleSignInClient.signInIntent
activityResultLauncher.launch(signInIntent)
}
private fun registeringActivityForGoogleSignIn() {
activityResultLauncher =
registerForActivityResult(ActivityResultContracts.StartActivityForResult(),
ActivityResultCallback { result ->
val resultCode = result.resultCode
val data = result.data
if (resultCode == RESULT_OK && data != null) {
val task: Task<GoogleSignInAccount> =
GoogleSignIn.getSignedInAccountFromIntent(data)
firebaseSignInWithGoogle(task)
}
})
}
private fun firebaseSignInWithGoogle(task: Task<GoogleSignInAccount>) {
try {
val account: GoogleSignInAccount = task.getResult(ApiException::class.java)
Toast.makeText(
applicationContext,
"成功使用 Gmail 帐户登录",
Toast.LENGTH_SHORT
).show()
// 打开主活动
val intent = Intent(this@LoginActivity, MainActivity::class.java)
startActivity(intent)
// 通过意图打开主活动后关闭登录页面
finish()
firebaseGoogleAccount(account)
} catch (e: ApiException) {
Toast.makeText(applicationContext, e.localizedMessage, Toast.LENGTH_SHORT).show()
}
}
private fun firebaseGoogleAccount(account: GoogleSignInAccount) {
// 创建一个 auth 凭证类的对象
val authCredential = GoogleAuthProvider.getCredential(
// 参数 1 -> account.idToken -> 每台设备都是唯一的,可以知道哪个设备已登录。
account.idToken, null
)
auth.signInWithCredential(authCredential).addOnCompleteListener { task ->
if (task.isSuccessful) {
// 如果登录成功,获取用户数据
Toast.makeText(applicationContext,"已登录",Toast.LENGTH_SHORT).show()
// 创建一个来自 Firebase 用户类的用户对象
//val user =
// auth.currentUser // 因此,已登录的用户分配给用户对象,即,当用户登录时,它会在其 Google 帐户中提供我们访问这些数据的机会。
// user?.email
} else {
Toast.makeText(applicationContext,task.exception?.localizedMessage,Toast.LENGTH_SHORT).show()
}
}
}
}
在选择一个 Google Gmail 帐户后,我希望能够导航到主活动,因为我在代码中使用了 "Intent"。
英文:
This is the code., what the issue I am facing was "After clicking on 'Sign In With Google' button, it displays me the available list of Gmail Accounts but after selecting one of the account it doesn't navigates me to the main activity.
In Firebase, I have enabled "Google Sign In" and also added "SHA -1" and "SHA-256" keys as a fingerprint to my project.
In logs, I notice "activityResume Trigger : not Whitelisted" and also in the build.gradle(:app) I have "minifyEnabled: false" as shown below
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
So, could you please help me out in figuring what is the issue. Thanks in Advance.
package com.turbotechnologies.quizgame
import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.Color
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.TextView
import android.widget.Toast
import androidx.activity.result.ActivityResultCallback
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import com.google.android.gms.auth.api.Auth
import com.google.android.gms.auth.api.signin.GoogleSignIn
import com.google.android.gms.auth.api.signin.GoogleSignInAccount
import com.google.android.gms.auth.api.signin.GoogleSignInClient
import com.google.android.gms.auth.api.signin.GoogleSignInOptions
import com.google.android.gms.common.api.ApiException
import com.google.android.gms.tasks.Task
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.GoogleAuthCredential
import com.google.firebase.auth.GoogleAuthProvider
import com.turbotechnologies.quizgame.R.drawable
import com.turbotechnologies.quizgame.databinding.ActivityLoginBinding
class LoginActivity : AppCompatActivity() {
lateinit var loginBinding: ActivityLoginBinding
private val auth: FirebaseAuth = FirebaseAuth.getInstance()
// Creating an object from google sign in client class
lateinit var googleSignInClient: GoogleSignInClient
lateinit var activityResultLauncher: ActivityResultLauncher<Intent>
@SuppressLint("SetTextI18n")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
loginBinding = ActivityLoginBinding.inflate(layoutInflater)
val view = loginBinding.root
setContentView(view)
val textForGoogleSignInButton = loginBinding.buttonGoogleSignIn.getChildAt(0) as TextView
// Changing the text of the google signIn button
textForGoogleSignInButton.text = "Continue with Google"
textForGoogleSignInButton.setTextColor(Color.BLACK)
textForGoogleSignInButton.textSize = 18F
textForGoogleSignInButton.setBackgroundResource(drawable.button_shape)
// register the activity
registeringActivityForGoogleSignIn()
loginBinding.buttonGoogleSignIn.setOnClickListener {
loginBinding.progressBar4.visibility = View.VISIBLE
signInGoogle()
}
}
private fun signInGoogle() {
val gso = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id))
.requestEmail().build()
googleSignInClient = GoogleSignIn.getClient(ths,gso)
signIn()
}
private fun signIn() {
val signInIntent = googleSignInClient.signInIntent
activityResultLauncher.launch(signInIntent)
}
private fun registeringActivityForGoogleSignIn() {
activityResultLauncher =
registerForActivityResult(ActivityResultContracts.StartActivityForResult(),
ActivityResultCallback { result ->
val resultCode = result.resultCode
val data = result.data
if (resultCode == RESULT_OK && data != null) {
val task: Task<GoogleSignInAccount> =
GoogleSignIn.getSignedInAccountFromIntent(data)
firebaseSignInWithGoogle(task)
}
})
}
private fun firebaseSignInWithGoogle(task: Task<GoogleSignInAccount>) {
try {
val account: GoogleSignInAccount = task.getResult(ApiException::class.java)
Toast.makeText(
applicationContext,
"Successfully logged in with Gmail account",
Toast.LENGTH_SHORT
).show()
// Opening the main activity
val intent = Intent(this@LoginActivity, MainActivity::class.java)
startActivity(intent)
// Closing the login page as we opened main activity using the intent
finish()
firebaseGoogleAccount(account)
} catch (e: ApiException) {
Toast.makeText(applicationContext, e.localizedMessage, Toast.LENGTH_SHORT).show()
}
}
private fun firebaseGoogleAccount(account: GoogleSignInAccount) {
// creating an object from the auth credential class
val authCredential = GoogleAuthProvider.getCredential(
// Parameter 1 -> account.idToken -> It is unique for each device and can know which device is logged in.
account.idToken, null
)
auth.signInWithCredential(authCredential).addOnCompleteListener { task ->
if (task.isSuccessful) {
// Retrieve the user data, if login is done
Toast.makeText(applicationContext,"Logged In",Toast.LENGTH_SHORT).show()
// Creating an user object from the firebase user class
//val user =
// auth.currentUser // Hence, logged in user is assigned to the user object i.e., When the user logs in, it gives us the opportunity to access this data in there google account.
// user?.email
} else {
Toast.makeText(applicationContext,task.exception?.localizedMessage,Toast.LENGTH_SHORT).show()
}
}
}
}
After selecting one of google gmail account, I need to navigated to the Main Activity as I used "Intent" for this in the code.
答案1
得分: 1
我检查了你的代码,没有错误。我甚至创建了一个新项目,只使用了你的代码,Google登录成功了。所以我认为问题是由于不同的原因引起的。首先,请确保将SHA-1密钥添加到你的Firebase项目中。如果没有,请添加它并重新下载新的google-services.json文件,并将其添加到你的项目中。然后,在Firebase控制台中,不要忘记选择Google作为登录方式,并在这里定义一个支持邮件地址。最后,请确保将Firebase auth和gms play services auth库添加到依赖部分。如果你确信已经完成了所有这些步骤,但仍然遇到问题,可以创建一个新的Android项目和一个新的Firebase项目,然后继续完成这些项目。
英文:
I checked your codes, there are no mistakes. I even created a new project and just used your codes and Google login was successful. So I think the problem is caused by a different reason. First, make sure you add the SHA-1 key to your Firebase project. If not, add it and re-download the new google-services.json file and add it to your project. Then, in the Firebase console, don't forget to choose Google from the Sign-in method and define a support mail address here. Finally, be sure to add the Firebase auth and gms play services auth libraries to the dependencies section. If you are sure that you have done all these and you are still having problems, create a new Android project and a new Firebase project and continue through these projects.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论