TechBuzzPro

Google Sign-In in Android: Step-by-Step Guide

· 6 min read · Phones & Tablets

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

Google Sign-In lets users log into your Android app with their existing Google account, removing the need for a separate username and password. This guide walks you through integrating it using the official Google Sign-In API for Android, from setting up the Google Cloud project to handling the sign-in flow in code. You'll need Android Studio, a Google Cloud Platform account (free tier is fine), and a basic understanding of Kotlin or Java.

What You'll Need

  • Android Studio (latest stable version recommended)
  • A Google Cloud Platform project (create one at console.cloud.google.com)
  • An Android device or emulator with Google Play services (for testing)
  • Basic knowledge of Android development (activities, layouts, Gradle)

Step-by-Step

  1. Set up your Google Cloud project: Go to the Google Cloud Console, create a new project or select an existing one. Then navigate to APIs & Services > OAuth consent screen. Choose External (or Internal if you're testing within your organization) and fill in the required fields (app name, support email). Save the consent screen.
  2. Create OAuth 2.0 credentials: In the same section, go to Credentials and click Create Credentials > OAuth client ID. Choose Android as the application type. You'll need your app's package name (e.g., com.example.myapp) and the SHA-1 signing certificate fingerprint. To get the SHA-1, open a terminal in Android Studio and run: keytool -list -v -keystore ~/.android/debug.keystore -alias androiddebugkey -storepass android -keypass android (for debug builds). Copy the SHA-1 value into the console. Click Create and note the generated client ID (it looks like 1234567890-abc123.apps.googleusercontent.com).
  3. Add dependencies to your app: In your app's build.gradle (Module: app), add the Google Sign-In dependency to the dependencies block: implementation 'com.google.android.gms:play-services-auth:20.7.0' (check the latest version on Google's Maven repository). Also, ensure your build.gradle has google() in the repositories block (usually already there). Sync the project.
  4. Add the OAuth client ID to your app: In your AndroidManifest.xml, inside the <application> tag, add a meta-data element with the client ID:
    <meta-data
        android:name="com.google.android.gms.auth.API_KEY"
        android:value="YOUR_CLIENT_ID" />
    Replace YOUR_CLIENT_ID with the one from step 2.
  5. Create a sign-in button: In your activity's layout XML, add a button (or use the pre-built com.google.android.gms.common.SignInButton). For example:
    <com.google.android.gms.common.SignInButton
        android:id="@+id/sign_in_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    Or use a regular Button and style it later.
  6. Configure the GoogleSignInOptions: In your activity's onCreate method, build the sign-in options. For basic sign-in (just the user's ID and email), use:
    GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
        .requestEmail()
        .build();
    If you need access to other Google APIs (like Drive), add .requestScopes(...) or .requestIdToken(...) as needed.
  7. Create a GoogleSignInClient: Using the options, get a client:
    GoogleSignInClient mGoogleSignInClient = GoogleSignIn.getClient(this, gso);
  8. Handle the sign-in button click: In your activity, set an OnClickListener on the button that starts the sign-in intent:
    findViewById(R.id.sign_in_button).setOnClickListener(v -> {
        Intent signInIntent = mGoogleSignInClient.getSignInIntent();
        startActivityForResult(signInIntent, RC_SIGN_IN);
    });
    Define RC_SIGN_IN as a constant (e.g., private static final int RC_SIGN_IN = 9001;).
  9. Handle the result: Override onActivityResult (or use the new Activity Result API if you prefer) to get the sign-in result:
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == RC_SIGN_IN) {
            Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
            handleSignInResult(task);
        }
    }
    In handleSignInResult, check if the task is successful:
    private void handleSignInResult(Task<GoogleSignInAccount> completedTask) {
        try {
            GoogleSignInAccount account = completedTask.getResult(ApiException.class);
            // Signed in successfully - use account.getEmail(), account.getId(), etc.
            updateUI(account);
        } catch (ApiException e) {
            // Sign-in failed - log the error code
            Log.w("SignIn", "signInResult:failed code=" + e.getStatusCode());
            updateUI(null);
        }
    }
  10. Check for existing sign-in: On app start, you can check if a user is already signed in using GoogleSignIn.getLastSignedInAccount(this). If it returns non-null, you can skip the sign-in screen.
  11. Sign out: Provide a sign-out button that calls mGoogleSignInClient.signOut() and then updates the UI.

Common Mistakes

  • Wrong SHA-1 fingerprint: Using the debug SHA-1 for a release build, or vice versa, will cause the sign-in to fail with a 12500 error. Always use the correct keystore for the build you're testing.
  • Missing OAuth consent screen configuration: If the consent screen isn't set up, you'll get an error when trying to sign in.
  • Using the wrong client ID: Copying the web client ID instead of the Android one, or mixing them up, will break the flow.
  • Not adding the meta-data tag: Forgetting to add the API key meta-data in the manifest can cause the API to fail silently.
  • Forgetting to call startActivityForResult from the activity: If you call it from a fragment, you need to use startActivityForResult from the fragment and handle it there, not in the activity.

Tips

  • Use the pre-built SignInButton for a consistent look that users recognize.
  • Always test on a real device, as the emulator sometimes has issues with Google Play services.
  • If you need the user's ID token for backend verification, add .requestIdToken(serverClientId) to your options, where serverClientId is your web client ID from the same project.
  • Keep your OAuth client ID in a secure place; don't hardcode it in a public repository if possible.
  • Use the Activity Result API (registerForActivityResult) for cleaner code if you're targeting modern Android versions.

Troubleshooting

If the sign-in fails, follow these steps in order:

  1. Check the error code: The ApiException gives a status code. Common ones: 12500 (sign-in failed, often due to configuration), 12501 (user cancelled), 10 (developer error, often wrong client ID or SHA-1).
  2. Verify your SHA-1 and package name: Re-check that the SHA-1 in the Google Cloud Console matches the keystore used to build the APK. For debug builds, it's the debug keystore; for release, it's your release keystore.
  3. Ensure the OAuth consent screen is complete: Go to the consent screen in the console and make sure the app name and support email are filled in, and the scopes are correct.
  4. Check the manifest meta-data: Confirm the meta-data tag is in the correct place (inside <application>) and the client ID is exactly right.
  5. Clear app data and retry: Sometimes a stale sign-in state causes issues. Uninstall the app, clear the Google Play services cache (Settings > Apps > Google Play services > Storage > Clear cache), and reinstall.
  6. Check internet connection: The sign-in requires network access. Ensure the device has a stable connection.
  7. Update Google Play services: On the device, make sure Google Play services is up to date.

Frequently Asked Questions

Do I need a backend server to use Google Sign-In?

No, you can use it purely for client-side authentication. However, if you need to verify the user's identity on your server, you'll need to request an ID token and send it to your backend for verification.

Can I use Google Sign-In with a fragment?

Yes, you can. Use startActivityForResult from the fragment, and handle the result in the fragment's onActivityResult. Make sure to use the fragment's startActivityForResult, not the activity's.

How do I get the user's profile picture?

After a successful sign-in, the GoogleSignInAccount object has a getPhotoUrl() method that returns a URL to the user's profile picture.

Why does my sign-in fail with error code 10?

Error 10 indicates a developer error. Most often it's because the SHA-1 fingerprint or package name in the Google Cloud Console doesn't match your app, or the client ID is wrong.

Can I use Google Sign-In in a release build?

Yes, but you must add the SHA-1 of your release keystore to the OAuth client in the Google Cloud Console. You can generate it with keytool -list -v -keystore your-release.keystore.

Is it possible to sign out and sign in as a different user?

Yes, call signOut() on the GoogleSignInClient to log out the current user, then the sign-in button will let you choose a different account.