Probably every app needs login and signup. Sometimes we need to collect very little data from the user. The user gets tired of entering this common information again and again in every app. To overcome these issues google provided login using google account. Google account contains a verity of information like name, email id, etc. By integrating Google sign-in users information can be collected with a single click. This article will demonstrate how to integrate Google Sign-In into your android application.
DOWNLOAD SOURCE CODE
DEMO
How to Integrate Google Sign In
While integrating google sign-in first of all we need to add/update google play services. Skip this step if you already have the latest Google Play services SDK.
1. Adding/Updating Google Play Services
Open SDK Manager in Android Studio File -> Setting -> Appearance & Behavior -> System Setting -> Android SDK. Check Google Play services and click Apply to add/update. The following image will give furthermore information.

2. Generating google-services.json file
Create a new project or open an existing File-> New Project. Enter the basic information of the project and create it. Since connecting to Google services never been easy. Follow the following steps to generate google-services.json file. This file has to be added to the app folder of the Android Studio project.
2.1 while Generating google-services.json file we need SHA-1 fingerprint. Go to View -> Tools Window -> Gradle. In Gradle panel go to Project name -> app -> Tasks -> android. Double click signingReport. Gradle Task will run.

2.2 Iside run panel report will generate. Toggle report to text using the toggle button shown in the image below.

2.3 Now you can see SHA-1 fingerprint as shown in the image below. Copy SHA-1 fingerprint.

2.4 Go to Google’s quick start guide click on GET CONFIGURATION FILE button.

2.5 Enter app name and Package name of the application.

2.6 Choose service as Google Sign-in. Enter SHA-1 fingerprint click on enable as shown in the image below.

2.7 Click Download google-services.json configuration file.

3. Adding google-services.json file to Android Studio Project
3.1 Move google-services.json file Project Root -> App folder as shown in the image below.

3.2 There are two build.gradle files. One is app level and another one is a project level build.gradle file as shown in the following image.

Add the dependency to your project-level build.gradle. Below is an example.
// Top-level build file where you can add configuration options common to all sub-projects/modules. buildscript { repositories { google() jcenter() } dependencies { classpath 'com.android.tools.build:gradle:3.0.0' /*Add dependency here */ classpath 'com.google.gms:google-services:3.1.0' } } allprojects { repositories { google() jcenter() } } task clean(type: Delete) { delete rootProject.buildDir }
Open app level build.gradle file. Apply google-services plugin at the bottom of the file. Add dependency to google play service auth library. There is one more library used here Picasso it is completely optional. We will use Picasso to load the user profile picture.
apply plugin: 'com.android.application' android { compileSdkVersion 26 defaultConfig { applicationId "com.loopwiki.googlesignin" minSdkVersion 15 targetSdkVersion 26 versionCode 1 versionName "1.0" testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } } dependencies { implementation fileTree(dir: 'libs', include: ['*.jar']) implementation 'com.android.support:appcompat-v7:26.1.0' implementation 'com.android.support.constraint:constraint-layout:1.0.2' implementation 'com.android.support:design:26.1.0' /*add Google Play services Auth library here*/ implementation 'com.google.android.gms:play-services-auth:11.6.0' /*Optional Add Piccasso library dependecy here to load profile Picture */ implementation 'com.squareup.picasso:picasso:2.5.2' } /*Add Apply Plugin here */ apply plugin: 'com.google.gms.google-services'
3.3 Copy and paste below string resource in your Values -> strings.xml file.
<resources> <string name="app_name">Google Sign In</string> <string name="action_settings">Settings</string> <string name="logged_in">Successfully Logged in with email</string> <string name="logged_out">Please Login using following button</string> </resources>
4. Creating Activity
4.1 Create a new layout -> content_main.xml. Add Textview for name And email. ImageView for displaying profile picture of the user. Two buttons for one for google sign in and another for logout.
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" app:layout_behavior="@string/appbar_scrolling_view_behavior" tools:context="com.loopwiki.googlesignin.MainActivity" tools:showIn="@layout/activity_main"> <! – Profile layout--> <LinearLayout android:layout_marginTop="32dp" android:id="@+id/llProfileLayout" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical"> <ImageView android:id="@+id/imageViewProfilePic" android:layout_width="84dp" android:layout_height="84dp" android:layout_gravity="center_horizontal" android:layout_marginTop="8dp" /> <TextView android:textAppearance="@style/TextAppearance.AppCompat.Large" android:id="@+id/textViewPersonName" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:layout_marginTop="4dp" /> <TextView android:textAppearance="@style/TextAppearance.AppCompat.Medium" android:id="@+id/textViewEmail" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:layout_marginTop="4dp" /> </LinearLayout> <!--Google Sign In button--> <com.google.android.gms.common.SignInButton android:id="@+id/sign_in_button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:layout_marginTop="8dp" /> <!--Logout button--> <Button android:id="@+id/buttonLogout" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:layout_marginTop="8dp" android:text="Logout" android:visibility="gone" /> </LinearLayout>
4.2 Create new layout -> activity_main.xml. This layout contains toolbar and content_main.xml.
<?xml version="1.0" encoding="utf-8"?> <android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.loopwiki.googlesignin.MainActivity"> <android.support.design.widget.AppBarLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:theme="@style/AppTheme.AppBarOverlay"> <android.support.v7.widget.Toolbar android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="?attr/actionBarSize" android:background="?attr/colorPrimary" app:popupTheme="@style/AppTheme.PopupOverlay" /> </android.support.design.widget.AppBarLayout> <include layout="@layout/content_main" /> </android.support.design.widget.CoordinatorLayout>
4.3 Create new class Package Name -> MainActivity.java. Add following code to it.
public class MainActivity extends AppCompatActivity { //Google sign in api Client GoogleSignInClient mGoogleSignInClient; //Define Request code for Sign In private int RC_SIGN_IN = 6; TextView textViewEmail; TextView textViewPersonName; ImageView imageViewProfilePic; LinearLayout llProfileLayout; //Logout Button declaration Button buttonLogout; //Sign in button Declaration SignInButton signInButton; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //Bind views Toolbar toolbar = findViewById(R.id.toolbar); textViewEmail = findViewById(R.id.textViewEmail); textViewPersonName = findViewById(R.id.textViewPersonName); imageViewProfilePic = findViewById(R.id.imageViewProfilePic); llProfileLayout = findViewById(R.id.llProfileLayout); signInButton = findViewById(R.id.sign_in_button); buttonLogout = findViewById(R.id.buttonLogout); setSupportActionBar(toolbar); //Build Google Sign in options GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN) .requestEmail() .build(); //get Sign in client mGoogleSignInClient = GoogleSignIn.getClient(this, gso); //get currently signed in user returns null if there is no logged in user GoogleSignInAccount account = GoogleSignIn.getLastSignedInAccount(this); //update ui updateUI(account); } //Method to signIn private void signIn() { Intent signInIntent = mGoogleSignInClient.getSignInIntent(); startActivityForResult(signInIntent, RC_SIGN_IN); } //method to sign out private void signOut() { mGoogleSignInClient.signOut() .addOnCompleteListener(this, new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { if (task.isSuccessful()) { updateUI(null); } } }); } //Handle sign in results private void handleSignInResult(Task<GoogleSignInAccount> completedTask) { try { GoogleSignInAccount account = completedTask.getResult(ApiException.class); // Signed in successfully, show authenticated UI. updateUI(account); } catch (ApiException e) { // The ApiException status code indicates the detailed failure reason. // Please refer to the GoogleSignInStatusCodes class reference for more information. updateUI(null); } } private void updateUI(GoogleSignInAccount account) { //Account is not null then user is logged in if (account != null) { buttonLogout.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { signOut(); } }); signInButton.setVisibility(View.GONE); buttonLogout.setVisibility(View.VISIBLE); textViewEmail.setText(account.getEmail()); textViewPersonName.setText(account.getDisplayName()); Picasso.with(this).load(account.getPhotoUrl()).fit().into(imageViewProfilePic); llProfileLayout.setVisibility(View.VISIBLE); } else { //user is not logged in // Set the dimensions of the sign-in button. signInButton.setSize(SignInButton.SIZE_WIDE); signInButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { signIn(); } }); signInButton.setVisibility(View.VISIBLE); buttonLogout.setVisibility(View.GONE); llProfileLayout.setVisibility(View.GONE); } } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); // Result returned from launching the Intent from GoogleSignInClient.getSignInIntent(...); if (requestCode == RC_SIGN_IN) { // The Task returned from this call is always completed, no need to attach // a listener. Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data); handleSignInResult(task); } } }
Breaking MainActivity
These lines are used to build GoogleSignInOptions.
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN) .requestEmail() .build(); //get Sign in client mGoogleSignInClient = GoogleSignIn.getClient(this, gso);
Check user is already logged in or not and update UI.
//get currently signed in user returns null if there is no logged in user GoogleSignInAccount account = GoogleSignIn.getLastSignedInAccount(this); //update ui updateUI(account); private void updateUI(GoogleSignInAccount account) { //Account is not null then user is logged in if (account != null) { buttonLogout.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { signOut(); } }); signInButton.setVisibility(View.GONE); buttonLogout.setVisibility(View.VISIBLE); textViewEmail.setText(account.getEmail()); textViewPersonName.setText(account.getDisplayName()); Picasso.with(this).load(account.getPhotoUrl()).fit().into(imageViewProfilePic); llProfileLayout.setVisibility(View.VISIBLE); } else { //user is not logged in // Set the dimensions of the sign-in button. signInButton.setSize(SignInButton.SIZE_WIDE); signInButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { signIn(); } }); signInButton.setVisibility(View.VISIBLE); buttonLogout.setVisibility(View.GONE); llProfileLayout.setVisibility(View.GONE); } }
Method to sign in, sign out the user.
//Method to signIn private void signIn() { Intent signInIntent = mGoogleSignInClient.getSignInIntent(); startActivityForResult(signInIntent, RC_SIGN_IN); } //method to sign out private void signOut() { mGoogleSignInClient.signOut() .addOnCompleteListener(this, new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { if (task.isSuccessful()) { updateUI(null); } } }); }
Now when users will log in using google account we will get a sign in result inside onActivityResult() method. Inside this method, we will check for the request code and send the result to handleSignInResult() method.
@Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); // Result returned from launching the Intent from GoogleSignInClient.getSignInIntent(...); if (requestCode == RC_SIGN_IN) { // The Task returned from this call is always completed, no need to attach // a listener. Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data); handleSignInResult(task); } }
Inside handle, result get the user account and update UI.
//Handle sign in results private void handleSignInResult(Task<GoogleSignInAccount> completedTask) { try { GoogleSignInAccount account = completedTask.getResult(ApiException.class); // Signed in successfully, show authenticated UI. updateUI(account); } catch (ApiException e) { // The ApiException status code indicates the detailed failure reason. // Please refer to the GoogleSignInStatusCodes class reference for more information. updateUI(null); } }
5. Run the application
Most of the emulators do not have Google Play Services installed on it. Now in Android Studio, some emulators have Google Play Services added install emulators which have play services icon shown in the image below.

If it won’t work you can run it on a real device.
6. Output


If you still have any queries, please post them in the comments section below, I will be happy to help you.