How To integrate Google Sign in to Your Android App - Hive Programmers

avatar

Greetings to my favorite science community online, StemSocial.

It's @skyehi and I'm back to continue my series on Android App Development Tutorials For Beginners.

In today's special episode, I'm going to teach you how to integrate Google Sign in to your Android App.

A lot of Apps these days require users to sign up with an account to store data, communicate or keep track of user progress.

Polish_20240117_134842400.jpgOriginal Image Source by Miguel Á. Padriñán from Pexels

YpihifdXP4WNbGMdjw7e3DuhJWBvCw4SfuLZsrnJYHEpsqZFkiGGNCQTayu6EytKdg7zA3LL2PbZxrJGpWk6ZoZvBcJrADNFmaFEHagho8WsASbAA8jrpnELSvRtvjVuMiU1C5ADFX1vJgcpDvNtue9Pq83tjBKX62dqT5UoxtDk.png

When building an Android App that would require user account creation, you could create an SQL database and set up your very own custom sign up or login system.

However, to make things easier for the App, you can easily integrate Google account login to either verify a user or allow users to create their account.

I hope you're excited about this particular episode guys, let's get started with our work shall we

Prerequisites

For the benefit of newcomers to Android App development or my series, I'll share with you the required softwares you need to be able to go through with this tutorial.

  • Android Studio IDE - the platform on which we'll develop this and all other Android Apps.

  • Java Development Kit, JDK - You need to install JDK correctly on your PC for your PC to be able to execute Java commands or codes.

  • Physical Android Device or Emulator - After building the App, we'll need to test it either on an emulator or a physical Android device.

If you have all these checked out, you're absolutely ready to go through with this tutorial

2dk2RRM2dZ8gKjXsrozapsD83FxL3Xbyyi5LFttAhrXxr16mCe4arfLHNDdHCBmaJroMz2VbLrf6Rxy9uPQm7Ts7EnXL4nPiXSE5vJWSfR53VcqDUrQD87CZSpt2RKZcmrYrze8KanjkfyS8XmMCcz4p33NZmfHE4S9oRo3wU2.png

Set up a Project in Google Cloud Console

Now guys before we start I'll assume you already have an App you wish to integrate Google Sign In feature into.

If you just want to learn how to do it for future purposes, then create a new project on Android Studio and configure the project details.

To integrate the Google login feature, we need to have a Google cloud console account.

There are simple steps to this.

  • First go to the Google Cloud Console website to create a new project which of course would be linked with the App you are trying to integrate Google Sign-in into.

  • After opening the website, follow the instructions to create a new project or perhaps select an existing one if you've already logged in before.

  • The next thing to do is to navigate to the "Credentials" page

  • On the credentials page, click on "Create Credentials" and choose "OAuth client ID"

  • Please select "Android" as the application type since we intend to integrate the Google login in an Android App

  • Please enter the correct package name and the SHA-1 signing certificate fingerprint of your app (you can get all this information from Android Studio)

After following these steps head over to your Android Studio App to continue.

I'll assume that you had already created a new Android project for your App before starting this tutorial.

YpihifdXP4WNbGMdjw7e3DuhJWBvCw4SfuLZsrnJYHEpsqZFkiGGNCQTayu6EytKdg7zA3LL2PbZxrJGpWk6ZoZvBcJrADNFmaFEHagho8WsASbAA8jrpnELSvRtvjVuMiU1C5ADFX1vJgcpDvNtue9Pq83tjBKX62dqT5UoxtDk.png

Configure your Android Project with Dependencies

Alright guys since we need the Google authentication services, we have to include the Google auth library to our project.

To do this, open your build.gradle (Module: app) file and add the Google services plugin.

Of course, depending on the time of implementing this feature, the version of the Google services might have changed. It's always recommended to use the latest one guys.

Here's how your dependency code should look like

dependencies {
    implementation 'com.google.android.gms:play-services-auth:19.2.0'
}

After you're done adding this dependency code, click on the "Sync" button and Android Studio will start downloading the library and integrating dependency service to your project.

YpihifdXP4WNbGMdjw7e3DuhJWBvCw4SfuLZsrnJYHEpsqZFkiGGNCQTayu6EytKdg7zA3LL2PbZxrJGpWk6ZoZvBcJrADNFmaFEHagho8WsASbAA8jrpnELSvRtvjVuMiU1C5ADFX1vJgcpDvNtue9Pq83tjBKX62dqT5UoxtDk.png

Add OAuth Client ID to your App

Now in order to connect your account or the new project created inside the Google Cloud Console to your App project on Android Studio, you need to add the OAuth Client ID to your App

To do this, we need to head over to our res/values/strings.xml file and add a whole new string resource for the client ID.

Simply create a string resource in the strings file and add your web client ID gotten from Google Cloud Console

Here's how the code should look like

<string name="google_web_client_id">YOUR_WEB_CLIENT_ID</string>

Replace "YOUR_WEB_CLIENT_ID" with the actual ID

YpihifdXP4WNbGMdjw7e3DuhJWBvCw4SfuLZsrnJYHEpsqZFkiGGNCQTayu6EytKdg7zA3LL2PbZxrJGpWk6ZoZvBcJrADNFmaFEHagho8WsASbAA8jrpnELSvRtvjVuMiU1C5ADFX1vJgcpDvNtue9Pq83tjBKX62dqT5UoxtDk.png

Request Internet Permission

Now guys since whatever App we would want to integrate Google Sign in into would probably need internet access to sign users in or up, we need to request internet permission.

This will be done inside our AndroidManifest.xml file.
We have done this over and over in our series so there's really no need to explain any further guys.

Here's how your permission request code should look like

<uses-permission android:name="android.permission.INTERNET" />

Include the Google Sign-In activity

Now besides requesting internet permission in Android Manifest, we need to also include the Google Sign-In activity.

Every activity we introduce in an Android App must be included in the Manifest. Usually when you create a whole new activity in Android Studio, by default, the activity is added automatically.

However if you had to create a custom activity, then you would have to include it manually otherwise the App could crash when you wish to run it.

So here's how you include the Google Sign-In activity in Manifest as well

<activity
    android:name="com.google.android.gms.auth.api.signin.internal.SignInHubActivity"
    android:theme="@android:style/Theme.Translucent.NoTitleBar"
    android:excludeFromRecents="true"
    android:exported="false" />

YpihifdXP4WNbGMdjw7e3DuhJWBvCw4SfuLZsrnJYHEpsqZFkiGGNCQTayu6EytKdg7zA3LL2PbZxrJGpWk6ZoZvBcJrADNFmaFEHagho8WsASbAA8jrpnELSvRtvjVuMiU1C5ADFX1vJgcpDvNtue9Pq83tjBKX62dqT5UoxtDk.png

Implement Google Sign-In in your Activity/Fragment

It's time for some real backend code guys. What we need to do to integrate a Google Sign-In feature in our App is to create a new Java fragment activity class to handle the entire sign-in process.

We will create a class and name it GoogleSignInClient to handle the sign-in process

Here's how the entire Google Sign-In code should look like

import com.google.android.gms.auth.api.signin.GoogleSignIn;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.common.api.ApiException;

// ...

GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
        .requestIdToken(getString(R.string.google_web_client_id))
        .requestEmail()
        .build();

GoogleSignInClient mGoogleSignInClient = GoogleSignIn.getClient(this, gso);

private void signIn() {
    Intent signInIntent = mGoogleSignInClient.getSignInIntent();
    startActivityForResult(signInIntent, RC_SIGN_IN);
}

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

private void handleSignInResult(Task<GoogleSignInAccount> completedTask) {
    try {
        GoogleSignInAccount account = completedTask.getResult(ApiException.class);
        // Signed in successfully, handle account details
        updateUI(account);
    } catch (ApiException e) {
        // Handle error
        Log.w(TAG, "signInResult:failed code=" + e.getStatusCode());
        updateUI(null);
    }
}

private void updateUI(GoogleSignInAccount account) {
    if (account != null) {
        // User is signed in, perform your desired actions
    } else {
        // User is signed out
    }
}

YpihifdXP4WNbGMdjw7e3DuhJWBvCw4SfuLZsrnJYHEpsqZFkiGGNCQTayu6EytKdg7zA3LL2PbZxrJGpWk6ZoZvBcJrADNFmaFEHagho8WsASbAA8jrpnELSvRtvjVuMiU1C5ADFX1vJgcpDvNtue9Pq83tjBKX62dqT5UoxtDk.png

Add Sign-Out Option

Of course if users can sign in to your App, they should be able to conveniently sign out of the App.

The sign out feature will be done in the same GoogleSignInClient . All I have done is to create another method or function for sign out and name it signOut()

Here's how to implement the sign-out functionality

private void signOut() {
    mGoogleSignInClient.signOut()
            .addOnCompleteListener(this, task -> {
                // Sign out successful, update UI
                updateUI(null);
            });
}

2dk2RRM2dZ8gKjXsrozapsD83FxL3Xbyyi5LFttAhrXxr16mCe4arfLHNDdHCBmaJroMz2VbLrf6Rxy9uPQm7Ts7EnXL4nPiXSE5vJWSfR53VcqDUrQD87CZSpt2RKZcmrYrze8KanjkfyS8XmMCcz4p33NZmfHE4S9oRo3wU2.png

Congratulations

Congratulations guys, you have successfully integrated Google Sign-In or login feature to your App. Now users will be able to sign up or sign in to your Android App using their Google account or Gmail accounts.

This is really good for Apps that wish to verify that a user is human or owns the gmail account.

In future episodes, we'll work on how Apps can send email verification codes to the user's Gmail account to verify that the user owns the account they're using as a login account.

Thank you so much for taking the time to read today's blog. I hope you enjoyed this particular tutorial or episode as always.

If you're having troubles with writing the codes or integrating any feature, please let me know in the comments.

Have A Great Day And Catch You Next Time On StemSocial. Goodbye 👨‍💻


You Can Follow Me @skyehi For More Like This And Others



0
0
0.000
1 comments
avatar

Thanks for your contribution to the STEMsocial community. Feel free to join us on discord to get to know the rest of us!

Please consider delegating to the @stemsocial account (85% of the curation rewards are returned).

Thanks for including @stemsocial as a beneficiary, which gives you stronger support. 
 

0
0
0.000