您必须先登录 FirebaseAuth。
您可以匿名登录,
但如果您想登录用户的 google id,请尝试这样。
我创建了一个易于使用的管理器类。
- 制作(您的)GoogleUserManager 类
object YourGoogleUserManager {
private lateinit var gso: GoogleSignInOptions
private lateinit var firebaseAuth: FirebaseAuth
fun init(context: Context) {
firebaseAuth = FirebaseAuth.getInstance()
gso = GoogleSignInOptions
.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(context.getString(R.string.default_web_client_id))
.build()
}
fun startGoogleSignInForResult(
fragment: Fragment,
onSuccess: (AuthResult) -> Unit,
onFail: (Exception) -> Unit
): ActivityResultLauncher<Intent> {
return fragment.registerForActivityResult(
ActivityResultContracts.StartActivityForResult()
) {
val task = GoogleSignIn.getSignedInAccountFromIntent(it.data)
handleGoogleSignInResult(task, onSuccess, onFail)
}
}
fun signIn(
activityResultLauncher: ActivityResultLauncher<Intent>,
activity: Activity
) {
val googleSignInClient = GoogleSignIn.getClient(activity, gso)
activityResultLauncher.launch(googleSignInClient.signInIntent)
}
private fun handleGoogleSignInResult(
task: Task<GoogleSignInAccount>,
onSuccess: (AuthResult) -> Unit,
onFail: (Exception) -> Unit
) {
try {
val account = task.getResult(ApiException::class.java)
val credential = GoogleAuthProvider.getCredential(account?.idToken, null)
firebaseAuth.signInWithCredential(credential)
.addOnSuccessListener {
CatHolicLogger.log("success to firebase google sign in")
onSuccess(it)
}
.addOnFailureListener {
CatHolicLogger.log("fail to firebase google sign in")
onFail(it)
}
} catch (e: ApiException) {
CatHolicLogger.log("fail to firebase google sign in")
onFail(e)
}
}
fun signOut() {
firebaseAuth.signOut()
}
}
- 在您的应用程序中初始化管理器。
class YourApplication : Application() {
...
override fun onCreate() {
super.onCreate()
initGoogleUserManager()
}
...
private fun initGoogleUserManager() {
YourGoogleUserManager.init(this)
}
}
- 在您的片段(或活动)中使用管理器
class YourFragment : Fragment() {
...
...
private val startGoogleSignInForResult =
YourGoogleUserManager.startGoogleSignInForResult(this, onSuccess = {
// your job after success to sign in
}, onFail = {
// your job after fail to sign in
})
...
...
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding.signInButton.setOnClickListener {
YourGoogleUserManager.signIn(startGoogleSignInForResult, requireActivity())
}
}
}