How to add Google Login button to your Android app using Kotlin
- December 06, 2019
- John Codeos
Today, I’m going to show you how to create a Google Sign-In button in Android using the Google Play Services Auth library.
Lets get started!
First, you need to have a Google account.
Go to https://console.developers.google.com/ and login with your account.
Press Select a project at the top left corner and in the new window press NEW PROJECT.
On the next page, give a name to your project and press CREATE
On the left side menu, go to OAuth consent screen and fill in the required fields and press SAVE
You don’t need to submit for verification because you don’t use any sensitive scope.
After that, from the left side menu, choose Credentials, press Create credentials and choose OAuth client ID from the dropdown menu.
On the next page, choose Android give the Name of your app, Signing-certificate fingerprint, Package Name, and press Create
Get SHA-1 signing-certificate fingerprint (Debug)
Go to Android Studio and press the Gradle button on the right side.
Choose your app module > Tasks > android > signingReport to generate the SHA-1 fingerprint for debug mode.
Get SHA-1 signing-certificate fingerprint (Release)
To get the SHA-1 fingerprint for release, go to your terminal and paste the following command.
Replace the YOUR_KEYSTORE_PATH with the path where your keystore file is, and the YOUR_APP_ALIAS_IN_KEYSTORE with the alias you gave for your app when you added it in your keystore file.
Now, go back choose again Credentials, press Create credentials and choose OAuth client ID to create a Web application
A new window will pop up with the OAuth Client ID that we are going to use later.
Creating the Google Login Button
First, you need to install Google Services.
Go to your project’s top-level build.gradle file and add Google’s Maven repo (if it’s not already exist)
Now, go to your app-level build.gradle file and add the Google Play Services Auth dependency.
Add a Button to your XML file. In this example, we have a button in the middle of the activity_main.xml.
In your Kotlin class of your Activity (In this example is the MainActivity), create the GoogleSignInClient and add a click listener to your button.
IMPORTANT: You need to use the Web Application Client ID and NOT the Android Client ID to avoid the well-known problem error code 10.
When the button is clicked, the app starts the sign-in intent, which prompts the user to sign in with a Google account.
After the successful auth, you get back the results with the onActivityResult method.
To sign out the user, call the following function:
..and to revoke access (This can be used when you have the ‘Delete my account’ option in the user’s profile):
You can find the final project here
If you have any questions feel free to DM me on Twitter @johncodeos or leave a comment below!