我正在尝试在我的Kotlin应用程序中实现google firebase登录,
这就是我所做的:
在Firebase中将SHA1添加到我项目的应用程序中。
在我的项目中实现了Firebase,并且已正确同步。
这是我使用的代码:
class LoginActivity : AppCompatActivity() {
val RC_SIGN_IN: Int = 1
lateinit var mGoogleSignInClient: GoogleSignInClient
lateinit var mGoogleSignInOptions: GoogleSignInOptions
private lateinit var firebaseAuth: FirebaseAuth
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_login)
setupUI()
configureGoogleSignIn()
firebaseAuth = FirebaseAuth.getInstance()
}
override fun onStart() {
super.onStart()
val user = FirebaseAuth.getInstance().currentUser
if (user != null) {
val mainActivityIntent = Intent(this, MainActivity::class.java)
startActivity(mainActivityIntent)
finish()
}
}
private fun configureGoogleSignIn() {
mGoogleSignInOptions = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id))
.requestEmail()
.build()
mGoogleSignInClient = GoogleSignIn.getClient(this, mGoogleSignInOptions)
}
private fun setupUI() {
google_button.setOnClickListener {
signIn()
}
}
private fun signIn() {
val signInIntent: Intent = mGoogleSignInClient.signInIntent
startActivityForResult(signInIntent, RC_SIGN_IN)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == RC_SIGN_IN) {
val task: Task<GoogleSignInAccount> = GoogleSignIn.getSignedInAccountFromIntent(data)
try {
val account = task.getResult(ApiException::class.java)
if (account != null) {
firebaseAuthWithGoogle(account)
}
} catch (e: ApiException) {
Toast.makeText(this, "Google sign in failed:(", Toast.LENGTH_LONG).show()
}
}
}
private fun firebaseAuthWithGoogle(acct: GoogleSignInAccount) {
val credential = GoogleAuthProvider.getCredential(acct.idToken, null)
firebaseAuth.signInWithCredential(credential).addOnCompleteListener {
if (it.isSuccessful) {
val mainActivityIntent = Intent(this, MainActivity::class.java)
startActivity(mainActivityIntent)
} else {
Toast.makeText(this, "Google sign in failed:(", Toast.LENGTH_LONG).show()
}
}
}
companion object {
fun getLaunchIntent(from: Context) = Intent(from, LoginActivity::class.java).apply {
addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK)
}
}
}
它停在一行
Toast.makeText(this, "Google sign in failed:(", Toast.LENGTH_LONG).show()
,这意味着auth请求流程有问题。有帮助吗?
答案 0 :(得分:0)
解决了!
整个问题是在Google developer console
中添加所有信息在 OAuth同意屏幕中,您将需要:
应用程序主页链接
应用程序隐私政策链接
应用程序服务条款链接(可选)
如果其中之一丢失,则登录将不起作用。