Hello to all, today we are going to learn how to implement Google Sign In authentication in our Android app and let user do Sign In in single click and do Sign Out also.
Google Sign-In lets users sign in to your Android app with their existing Google account and get their profile information like name, email, profile pic and other details.
1. Add the dependency to your project-level build.gradle:
1 |
classpath 'com.google.gms:google-services:3.1.0' |
2. Add the plugin to your app-level build.gradle:
1 |
apply plugin: 'com.google.gms.google-services' |
In your app-level build.gradle file, declare Google Play Services as a dependency:
1 |
compile 'com.google.android.gms:play-services-auth:11.6.2' |
Finally your app-level build.gradle will look like below:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
apply plugin: 'com.android.application' android { compileSdkVersion 26 defaultConfig { applicationId "com.android_google_sign_in_demo" minSdkVersion 14 targetSdkVersion 26 versionCode 1 versionName "1.0" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } } dependencies { implementation fileTree(include: ['*.jar'], dir: 'libs') implementation 'com.android.support:appcompat-v7:26.1.0' //dependency for google sign in compile 'com.google.android.gms:play-services-auth:11.6.2' //dependency to load image url over image view implementation 'com.squareup.picasso:picasso:2.5.2' } //plugin for google services apply plugin: 'com.google.gms.google-services' |
Since we will load user profile pic so we will be needing Picasso dependency also.
To get the configuration file go to this link and follow the Video tutorial given above.
Now after getting configuration file, copy and paste the .json file under app directory and follow the below steps to Add Google Sign In in your app.
1. Create an xml layout naming activity_main.xml and add the below code to it. In this layout i have taken two Button one is for inbuilt or default Google Sign In Button and second one custom Sign In Button and a TextView and ImageView to display user information.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 |
<?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" android:padding="16dp" tools:context="com.android_google_sign_in_demo.MainActivity"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/default_sign_in_button" android:textColor="@color/colorPrimary" android:textSize="14sp" /> <!-- add default google sign in button type of button size : icon_only, wide and standard --> <com.google.android.gms.common.SignInButton android:id="@+id/default_google_sign_in_button" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="10dp" app:buttonSize="wide" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="20dp" android:text="@string/custom_sign_in_button" android:textColor="@color/colorPrimary" android:textSize="14sp" /> <!-- custom google sign in button --> <Button android:id="@+id/custom_sign_in_button" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="10dp" android:background="@color/colorPrimary" android:onClick="customGoogleSignIn" android:text="@string/sign_in" android:textColor="@android:color/white" /> <!-- image view to show user profile image --> <ImageView android:id="@+id/user_profile_image_view" android:layout_width="120dp" android:layout_height="120dp" android:layout_gravity="center_horizontal" android:layout_marginTop="20dp" /> <!-- text view to show user details --> <TextView android:id="@+id/user_details_label" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="10dp" android:textColor="@color/colorPrimary" android:textSize="15sp" /> </LinearLayout> |
2. After creating follow the below steps to Add Google Sign-In and Sign-Out :
1 2 3 4 5 6 7 8 9 10 11 |
private void configureGoogleSignIn() { // Configure sign-in to request the user's ID, email address, and basic // profile. ID and basic profile are included in DEFAULT_SIGN_IN. GoogleSignInOptions gso = new GoogleSignInOptions .Builder(GoogleSignInOptions.DEFAULT_SIGN_IN) .requestEmail()//request email id .build(); // Build a GoogleSignInClient with the options specified by gso. mGoogleSignInClient = GoogleSignIn.getClient(this, gso); } |
1 2 3 4 |
private void doGoogleSignIn() { Intent signInIntent = mGoogleSignInClient.getSignInIntent(); startActivityForResult(signInIntent, RC_SIGN_IN);//pass the declared request code here } |
1 2 3 4 5 6 7 8 9 10 11 12 |
@Override protected 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); //method to handle google sign in result handleSignInResult(task); } } |
The GoogleSignInAccount object contains information about the signed-in user, such as the user’s name.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
private void handleSignInResult(Task<GoogleSignInAccount> completedTask) { try { GoogleSignInAccount account = completedTask.getResult(ApiException.class); // Signed in successfully, show authenticated UI. getProfileInformation(account); //show toast Toast.makeText(this, "Google Sign In Successful.", Toast.LENGTH_SHORT).show(); } catch (ApiException e) { // The ApiException status code indicates the detailed failure reason. // Please refer to the GoogleSignInStatusCodes class reference for more information. Log.e(TAG, "signInResult:failed code=" + e.getStatusCode()); //show toast Toast.makeText(this, "Failed to do Sign In : " + e.getStatusCode(), Toast.LENGTH_SHORT).show(); //update Ui for this getProfileInformation(null); } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
GoogleSignInAccount acct = GoogleSignIn.getLastSignedInAccount(this); if (acct != null) { //user display name String personName = acct.getDisplayName(); //user first name String personGivenName = acct.getGivenName(); //user last name String personFamilyName = acct.getFamilyName(); //user email id String personEmail = acct.getEmail(); //user unique id String personId = acct.getId(); //user profile pic Uri personPhoto = acct.getPhotoUrl(); //show the user details userDetailLabel.setText("ID : " + personId + "\nDisplay Name : " + personName + "\nFull Name : " + personGivenName + " " + personFamilyName + "\nEmail : " + personEmail); //show the user profile pic Picasso.with(this).load(personPhoto).fit().placeholder(R.mipmap.ic_launcher_round).into(userProfileImageView); //change the text of Custom Sign in button to sign out customSignInButton.setText(getResources().getString(R.string.sign_out)); //show the label and image view userDetailLabel.setVisibility(View.VISIBLE); userProfileImageView.setVisibility(View.VISIBLE); } |
1 2 3 4 5 6 7 8 9 10 |
private void doGoogleSignOut() { mGoogleSignInClient.signOut() .addOnCompleteListener(this, new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { Toast.makeText(MainActivity.this, "Google Sign Out done.", Toast.LENGTH_SHORT).show(); revokeAccess(); } }); } |
1 2 3 4 5 6 7 8 9 10 |
private void revokeAccess() { mGoogleSignInClient.revokeAccess() .addOnCompleteListener(this, new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { Toast.makeText(MainActivity.this, "Google access revoked.", Toast.LENGTH_SHORT).show(); getProfileInformation(null); } }); } |
1 2 3 4 5 6 7 8 9 10 |
@Override protected void onStart() { super.onStart(); //SILENT SIGN IN // Check for existing Google Sign In account, if the user is already signed in // the GoogleSignInAccount will be non-null. GoogleSignInAccount account = GoogleSignIn.getLastSignedInAccount(this); //update the UI if user has already sign in with the google for this app getProfileInformation(account); } |
3. Full MainActivity code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 |
package com.android_google_sign_in_demo; import android.content.Intent; import android.net.Uri; import android.support.annotation.NonNull; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; 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.GoogleSignInClient; import com.google.android.gms.auth.api.signin.GoogleSignInOptions; import com.google.android.gms.common.SignInButton; import com.google.android.gms.common.api.ApiException; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.squareup.picasso.Picasso; public class MainActivity extends AppCompatActivity { private static final String TAG = MainActivity.class.getSimpleName(); private static final int RC_SIGN_IN = 111;//google sign in request code private GoogleSignInClient mGoogleSignInClient;//google sign in client private SignInButton defaultSignInButton; private Button customSignInButton; private TextView userDetailLabel; private ImageView userProfileImageView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); findViews(); configureGoogleSignIn(); } /** * find all views and implement click event over default sign in button */ private void findViews() { defaultSignInButton = findViewById(R.id.default_google_sign_in_button); customSignInButton = findViewById(R.id.custom_sign_in_button); userDetailLabel = findViewById(R.id.user_details_label); userProfileImageView = findViewById(R.id.user_profile_image_view); defaultSignInButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { doSignInSignOut(); } }); } /** * configure google sign in */ private void configureGoogleSignIn() { // Configure sign-in to request the user's ID, email address, and basic // profile. ID and basic profile are included in DEFAULT_SIGN_IN. GoogleSignInOptions gso = new GoogleSignInOptions .Builder(GoogleSignInOptions.DEFAULT_SIGN_IN) .requestEmail()//request email id .build(); // Build a GoogleSignInClient with the options specified by gso. mGoogleSignInClient = GoogleSignIn.getClient(this, gso); } @Override protected void onStart() { super.onStart(); //SILENT SIGN IN // Check for existing Google Sign In account, if the user is already signed in // the GoogleSignInAccount will be non-null. GoogleSignInAccount account = GoogleSignIn.getLastSignedInAccount(this); //update the UI if user has already sign in with the google for this app getProfileInformation(account); } /** * custom sign in button click event * * @param view custom button */ public void customGoogleSignIn(View view) { doSignInSignOut(); } /** * method to do Sign In or Sign Out on the basis of account exist or not */ private void doSignInSignOut() { //get the last sign in account GoogleSignInAccount account = GoogleSignIn.getLastSignedInAccount(this); //if account doesn't exist do login else do sign out if (account == null) doGoogleSignIn(); else doGoogleSignOut(); } /** * do google sign in */ private void doGoogleSignIn() { Intent signInIntent = mGoogleSignInClient.getSignInIntent(); startActivityForResult(signInIntent, RC_SIGN_IN);//pass the declared request code here } @Override protected 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); //method to handle google sign in result handleSignInResult(task); } } /** * method to handle google sign in result * * @param completedTask from google onActivityResult */ private void handleSignInResult(Task<GoogleSignInAccount> completedTask) { try { GoogleSignInAccount account = completedTask.getResult(ApiException.class); // Signed in successfully, show authenticated UI. getProfileInformation(account); //show toast Toast.makeText(this, "Google Sign In Successful.", Toast.LENGTH_SHORT).show(); } catch (ApiException e) { // The ApiException status code indicates the detailed failure reason. // Please refer to the GoogleSignInStatusCodes class reference for more information. Log.e(TAG, "signInResult:failed code=" + e.getStatusCode()); //show toast Toast.makeText(this, "Failed to do Sign In : " + e.getStatusCode(), Toast.LENGTH_SHORT).show(); //update Ui for this getProfileInformation(null); } } /** * method to fetch user profile information from GoogleSignInAccount * * @param acct googleSignInAccount */ private void getProfileInformation(GoogleSignInAccount acct) { //if account is not null fetch the information if (acct != null) { //user display name String personName = acct.getDisplayName(); //user first name String personGivenName = acct.getGivenName(); //user last name String personFamilyName = acct.getFamilyName(); //user email id String personEmail = acct.getEmail(); //user unique id String personId = acct.getId(); //user profile pic Uri personPhoto = acct.getPhotoUrl(); //show the user details userDetailLabel.setText("ID : " + personId + "\nDisplay Name : " + personName + "\nFull Name : " + personGivenName + " " + personFamilyName + "\nEmail : " + personEmail); //show the user profile pic Picasso.with(this).load(personPhoto).fit().placeholder(R.mipmap.ic_launcher_round).into(userProfileImageView); //change the text of Custom Sign in button to sign out customSignInButton.setText(getResources().getString(R.string.sign_out)); //show the label and image view userDetailLabel.setVisibility(View.VISIBLE); userProfileImageView.setVisibility(View.VISIBLE); } else { //if account is null change the text back to Sign In and hide the label and image view customSignInButton.setText(getResources().getString(R.string.sign_in)); userDetailLabel.setVisibility(View.GONE); userProfileImageView.setVisibility(View.GONE); } } /** * method to do google sign out * This code clears which account is connected to the app. To sign in again, the user must choose their account again. */ private void doGoogleSignOut() { mGoogleSignInClient.signOut() .addOnCompleteListener(this, new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { Toast.makeText(MainActivity.this, "Google Sign Out done.", Toast.LENGTH_SHORT).show(); revokeAccess(); } }); } /** * DISCONNECT ACCOUNTS * method to revoke access from this app * call this method after successful sign out * <p> * It is highly recommended that you provide users that signed in with Google the ability to disconnect their Google account from your app. If the user deletes their account, you must delete the information that your app obtained from the Google APIs */ private void revokeAccess() { mGoogleSignInClient.revokeAccess() .addOnCompleteListener(this, new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { Toast.makeText(MainActivity.this, "Google access revoked.", Toast.LENGTH_SHORT).show(); getProfileInformation(null); } }); } } |
4. Finally all done , now you can also add Google Sing-In to your Android app.
Thanks.
Subscribe to us and get the latest news.