This documentation provides guidance on implementing Google Sign-In in a Jetpack Compose application. The provided code demonstrates the integration of Google Sign-In using the Google Sign-In API and Firebase Authentication.
Before implementing Google Sign-In, make sure you have the following:
- A Google Cloud Platform (GCP) project with the necessary credentials.
- Firebase project set up with Firebase Authentication.
Ensure you have the required dependencies in your build.gradle file:
implementation "androidx.activity:activity-compose:1.3.0-alpha08"
implementation "com.google.android.gms:play-services-auth:19.0.0"
implementation "com.google.firebase:firebase-auth:23.0.0"Add the google-services.json file to your app module. This file contains configuration details for your Firebase project.
Ensure that you include your web client ID as well. You can obtain it from the Firebase Console by navigating to Authentication > Sign-in Method > Google > Web SDK Implementation.
Add Google Sign-in Launcher inside a composable:
@Composable
fun SignInScreen() {
// Initialize the Google Sign-In launcher using the ActivityResultContracts
val googleSignInLauncher =
rememberLauncherForActivityResult(contract = ActivityResultContracts.StartActivityForResult()
) { result ->
if (result.resultCode == Activity.RESULT_OK) {
val task = GoogleSignIn.getSignedInAccountFromIntent(result.data)
handleSignInResult(task, context)
}
}
// ... (Your existing code)
}
Implement a function to initiate Google Sign-in:
fun signInWithGoogle(
googleSignInLauncher: ManagedActivityResultLauncher<Intent, ActivityResult>,
context: Context
) {
val webClientID = "YOUR_WEB_CLIENT_ID"
val googleSignInOptions = GoogleSignInOptions
.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(webClientID)
.requestEmail()
.build()
val googleSignInClient = GoogleSignIn.getClient(context, googleSignInOptions)
// hack-ish way to re-select google account during sign-in
googleSignInClient.signOut()
val signInIntent = googleSignInClient.signInIntent
googleSignInLauncher.launch(signInIntent)
}
Implement the function to handle the result of Google Sign-In:
fun handleSignInResult(completedTask: Task<GoogleSignInAccount>, context: Context) {
try {
val account = completedTask.getResult(ApiException::class.java)
firebaseAuthWithGoogle(account.idToken!!, context)
} catch (e: ApiException) {
toast("Error: ${e.statusCode} ${e.message}", context)
}
}
Implement the function for Firebase Authentication using the obtained Google Sign-In account:
private fun firebaseAuthWithGoogle(idToken: String?, context: Context) {
val auth: FirebaseAuth = FirebaseAuth.getInstance()
val credential = GoogleAuthProvider.getCredential(idToken, null)
auth.signInWithCredential(credential)
.addOnCompleteListener { task ->
if (task.isSuccessful) {
// get email from currently signed-in user
val email = auth.currentUser?.email ?: ""
toast("Your email: $email", context)
} else {
toast("Failed to sign-in", context)
}
}
}

