Fading Coder

One Final Commit for the Last Sprint

Home > Notes > Content

Integrating Google Sign-In in Android Applications

Notes Oct 10 17

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
    });
}

Related Articles

Designing Alertmanager Templates for Prometheus Notifications

How to craft Alertmanager templates to format alert messages, improving clarity and presentation. Alertmanager uses Go’s text/template engine with additional helper functions. Alerting rules referenc...

Deploying a Maven Web Application to Tomcat 9 Using the Tomcat Manager

Tomcat 9 does not provide a dedicated Maven plugin. The Tomcat Manager interface, however, is backward-compatible, so the Tomcat 7 Maven Plugin can be used to deploy to Tomcat 9. This guide shows two...

Skipping Errors in MySQL Asynchronous Replication

When a replica halts because the SQL thread encounters an error, you can resume replication by skipping the problematic event(s). Two common approaches are available. Methods to Skip Errors 1) Skip a...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.