Integrating Google Sign-In in Android Applications
Cloud Console Configuration
Navigate to the Google Cloud Console. Create an OAuth 2.0 Client ID. You will need the Web application Client ID for the Android client initialization. Additionally, generate an Android Client ID mapped to your application's package name and SHA-1 signing certificate.
Project Dependencies
Ensure your build.gradle file includes the Google Maven repository (google()). Then, add the authentication library to the dependencies block:
implementation 'com.google.android.gms:play-services-auth:20.2.0'Configuring the Sign-In Client
Initialize the authentication client using the Web Client ID obtained earlier.
private void setupGoogleAuth() {
GoogleSignInOptions signInConfigs = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken("YOUR_WEB_CLIENT_ID")
.requestEmail()
.build();
googleAuthClient = GoogleSignIn.getClient(this, signInConfigs);
}Initiating the Login Process
Before launching the sign-in intent, check if a user is already authenticated. If not, start the authentication flow.
public static void startGoogleLogin() {
GoogleSignInAccount cachedAccount = GoogleSignIn.getLastSignedInAccount(getActivity().getApplicationContext());
if (cachedAccount == null) {
Intent authIntent = googleAuthClient.getSignInIntent();
getActivity().startActivityForResult(authIntent, AUTH_REQUEST_CODE);
} else {
handleAuthResult(cachedAccount);
}
}Processing the Authentication Result
Capture the response from the sign-in activity and extract the user data.
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode != RESULT_OK) return;
if (requestCode == AUTH_REQUEST_CODE) {
Task<GoogleSignInAccount> authTask = GoogleSignIn.getSignedInAccountFromIntent(data);
try {
GoogleSignInAccount authenticatedAccount = authTask.getResult(ApiException.class);
if (authenticatedAccount != null && !authenticatedAccount.isExpired()) {
handleAuthResult(authenticatedAccount);
}
} catch (ApiException e) {
e.printStackTrace();
}
}
}
private static void handleAuthResult(GoogleSignInAccount authenticatedAccount) {
String authIdToken = authenticatedAccount.getIdToken();
String accountId = authenticatedAccount.getId();
String accountName = authenticatedAccount.getDisplayName();
String avatarUrl = authenticatedAccount.getPhotoUrl().toString();
}Terminating the Session
To log the user out, invoke the sign-out method on the client.
public static void disconnectGoogle() {
googleAuthClient.signOut().addOnCompleteListener(getActivity(), task -> {
// Session terminated successfully
});
}