Introduction

Ninety percent of people use Android smartphones. There are a lot of third party applications authenticating our users by using Google authentication API. I will show you how to use Google authentication API in your Application, using Android Studio. Android is a kernel-based operating system. It allows the user to modify the GUI components and the source code.
Requirements
Download link (Android Studio) https//developer.android.com/studio/index.html

Steps to be followed are given below

Carefully follow my steps to use Google authentication API in your Application, using an Android Studio and I have included the source code given below.
Step 1
Open Android Studio and start the new project.
android
Step 2
Put the Application name and company domain. If you wish to use C++ to code the project, mark the Include C++ support, followed by clicking Next.
android
Step 3
Select Android minimum SDK. Afterward, you chose the minimum SDK and it will show the approximate percentage of people, who use SDK, followed by clicking Next.
android
Step 4
Choose the empty activity, followed by clicking Next.
android
Step 5
Put the activity name and layout name. Android Studio basically takes Java class name and you need to provide the activity name. Click Finish.
android
Step 6
The website link is https//developers.google.com/identity/sign-in/android/start.
Sign in with your Gmail account and create a project.
Go to the link above and click GET A CONFIGURATION FILE
android
Step 9
Put your app name and unique app package name.
android
Step 10
Select your country region and click Choose and configure Service.
android
Step 11
Your API file was ready to use and it will be shown in Green color. After clicking Google sign-in, the screen given below will come.
android
Step 12
Now, you must provide your app SHA1 value. Go to your project (Gradle project) and double click SigningReport. It will show you the SHA1 value. Copy the value.
android
android
Step 13
Paste SHA1 value and download your googleservice.json file.
android
android
android
Step 14
Add the Google-services.json file into your app folder.
android
Step 15
Go to activity_main.xml, followed by clicking the text bottom. This XML file contains the designing code for an Android app. Into the activity_main.xml, copy and paste the code given below.
activity_main.xml code
  1. <?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3. xmlns:tools="http://schemas.android.com/tools"
  4. android:layout_width="match_parent"
  5. android:layout_height="match_parent"
  6. android:orientation="vertical"
  7. android:padding="@dimen/activity_horizontal_margin"
  8. android:gravity="center"
  9. tools:context=".MainActivity">
  10. <LinearLayout
  11. android:id="@+id/llProfile"
  12. android:layout_width="fill_parent"
  13. android:layout_height="wrap_content"
  14. android:layout_marginBottom="20dp"
  15. android:orientation="horizontal"
  16. android:visibility="gone"
  17. android:weightSum="3">
  18. <ImageView
  19. android:id="@+id/imgProfilePic"
  20. android:layout_width="80dp"
  21. android:layout_height="wrap_content"
  22. android:layout_weight="1" />
  23. <LinearLayout
  24. android:layout_width="wrap_content"
  25. android:layout_height="wrap_content"
  26. android:layout_marginLeft="10dp"
  27. android:layout_weight="2"
  28. android:orientation="vertical">
  29. <TextView
  30. android:id="@+id/txtName"
  31. android:layout_width="wrap_content"
  32. android:layout_height="wrap_content"
  33. android:padding="5dp"
  34. android:textSize="20dp" />
  35. <TextView
  36. android:id="@+id/txtEmail"
  37. android:layout_width="wrap_content"
  38. android:layout_height="wrap_content"
  39. android:padding="5dp"
  40. android:textSize="18dp" />
  41. </LinearLayout>
  42. </LinearLayout>
  43. <com.google.android.gms.common.SignInButton
  44. android:id="@+id/btn_sign_in"
  45. android:layout_width="fill_parent"
  46. android:layout_height="wrap_content"
  47. android:layout_marginBottom="20dp" />
  48. <Button
  49. android:id="@+id/btn_sign_out"
  50. android:layout_width="fill_parent"
  51. android:layout_height="wrap_content"
  52. android:layout_marginBottom="10dp"
  53. android:text="@string/btn_logout_from_google"
  54. android:visibility="gone" />
  55. </LinearLayout>
Step 16
In MainActivity.java, copy and paste the code given below. Java programming is the backend language for Android. Do not replace your package name, else an app will not run. The code given below contains my package name.
  1. package com.nikshit.gplusdemo;
  2. import android.app.ProgressDialog;
  3. import android.content.Intent;
  4. import android.os.Bundle;
  5. import android.support.annotation.NonNull;
  6. import android.support.v7.app.AppCompatActivity;
  7. import android.util.Log;
  8. import android.view.View;
  9. import android.widget.Button;
  10. import android.widget.ImageView;
  11. import android.widget.LinearLayout;
  12. import android.widget.TextView;
  13. import com.bumptech.glide.Glide;
  14. import com.bumptech.glide.load.engine.DiskCacheStrategy;
  15. import com.google.android.gms.auth.api.Auth;
  16. import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
  17. import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
  18. import com.google.android.gms.auth.api.signin.GoogleSignInResult;
  19. import com.google.android.gms.common.ConnectionResult;
  20. import com.google.android.gms.common.SignInButton;
  21. import com.google.android.gms.common.api.GoogleApiClient;
  22. import com.google.android.gms.common.api.OptionalPendingResult;
  23. import com.google.android.gms.common.api.ResultCallback;
  24. import com.google.android.gms.common.api.Status;
  25. public class MainActivity extends AppCompatActivity implements View.OnClickListener, GoogleApiClient.OnConnectionFailedListener {
  26. private static final String TAG = MainActivity.class.getSimpleName();
  27. private static final int RC_SIGN_IN = 420;
  28. private GoogleApiClient mGoogleApiClient;
  29. private ProgressDialog mProgressDialog;
  30. private SignInButton btnSignIn;
  31. private Button btnSignOut;
  32. private LinearLayout llProfileLayout;
  33. private ImageView imgProfilePic;
  34. private TextView txtName, txtEmail;
  35. @Override
  36. protected void onCreate(Bundle savedInstanceState) {
  37. super.onCreate(savedInstanceState);
  38. setContentView(R.layout.activity_main);
  39. initializeControls();
  40. initializeGPlusSettings();
  41. }
  42. private void initializeControls(){
  43. btnSignIn = (SignInButton) findViewById(R.id.btn_sign_in);
  44. btnSignOut = (Button) findViewById(R.id.btn_sign_out);
  45. llProfileLayout = (LinearLayout) findViewById(R.id.llProfile);
  46. imgProfilePic = (ImageView) findViewById(R.id.imgProfilePic);
  47. txtName = (TextView) findViewById(R.id.txtName);
  48. txtEmail = (TextView) findViewById(R.id.txtEmail);
  49. btnSignIn.setOnClickListener(this);
  50. btnSignOut.setOnClickListener(this);
  51. }
  52. private void initializeGPlusSettings(){
  53. GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
  54. .requestEmail()
  55. .build();
  56. mGoogleApiClient = new GoogleApiClient.Builder(this)
  57. .enableAutoManage(this, this)
  58. .addApi(Auth.GOOGLE_SIGN_IN_API, gso)
  59. .build();
  60. // Customizing G+ button
  61. btnSignIn.setSize(SignInButton.SIZE_STANDARD);
  62. btnSignIn.setScopes(gso.getScopeArray());
  63. }
  64. private void signIn() {
  65. Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
  66. startActivityForResult(signInIntent, RC_SIGN_IN);
  67. }
  68. private void signOut() {
  69. Auth.GoogleSignInApi.signOut(mGoogleApiClient).setResultCallback(
  70. new ResultCallback<Status>() {
  71. @Override
  72. public void onResult(Status status) {
  73. updateUI(false);
  74. }
  75. });
  76. }
  77. private void handleGPlusSignInResult(GoogleSignInResult result) {
  78. Log.d(TAG, "handleSignInResult:" + result.isSuccess());
  79. if (result.isSuccess()) {
  80. // Signed in successfully, show authenticated UI.
  81. GoogleSignInAccount acct = result.getSignInAccount();
  82. //Fetch values
  83. String personName = acct.getDisplayName();
  84. String personPhotoUrl = acct.getPhotoUrl().toString();
  85. String email = acct.getEmail();
  86. String familyName = acct.getFamilyName();
  87. Log.e(TAG, "Name: " + personName +
  88. ", email: " + email +
  89. ", Image: " + personPhotoUrl +
  90. ", Family Name: " + familyName);
  91. //Set values
  92. txtName.setText(personName);
  93. txtEmail.setText(email);
  94. //Set profile pic with the help of Glide
  95. Glide.with(getApplicationContext()).load(personPhotoUrl)
  96. .thumbnail(0.5f)
  97. .crossFade()
  98. .diskCacheStrategy(DiskCacheStrategy.ALL)
  99. .into(imgProfilePic);
  100. updateUI(true);
  101. } else {
  102. // Signed out, show unauthenticated UI.
  103. updateUI(false);
  104. }
  105. }
  106. @Override
  107. public void onClick(View v) {
  108. int id = v.getId();
  109. switch (id) {
  110. case R.id.btn_sign_in:
  111. signIn();
  112. break;
  113. case R.id.btn_sign_out:
  114. signOut();
  115. break;
  116. }
  117. }
  118. @Override
  119. public void onActivityResult(int requestCode, int resultCode, Intent data) {
  120. super.onActivityResult(requestCode, resultCode, data);
  121. // Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...);
  122. if (requestCode == RC_SIGN_IN) {
  123. GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
  124. handleGPlusSignInResult(result);
  125. }
  126. }
  127. @Override
  128. public void onStart() {
  129. super.onStart();
  130. OptionalPendingResult<GoogleSignInResult> opr = Auth.GoogleSignInApi.silentSignIn(mGoogleApiClient);
  131. if (opr.isDone()) {
  132. // If the user's cached credentials are valid, the OptionalPendingResult will be "done"
  133. // and the GoogleSignInResult will be available instantly.
  134. Log.d(TAG, "Got cached sign-in");
  135. GoogleSignInResult result = opr.get();
  136. handleGPlusSignInResult(result);
  137. } else {
  138. // If the user has not previously signed in on this device or the sign-in has expired,
  139. // this asynchronous branch will attempt to sign in the user silently. Cross-device
  140. // single sign-on will occur in this branch.
  141. showProgressDialog();
  142. opr.setResultCallback(new ResultCallback<GoogleSignInResult>() {
  143. @Override
  144. public void onResult(GoogleSignInResult googleSignInResult) {
  145. hideProgressDialog();
  146. handleGPlusSignInResult(googleSignInResult);
  147. }
  148. });
  149. }
  150. }
  151. @Override
  152. public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
  153. // An unresolvable error has occurred and Google APIs (including Sign-In) will not
  154. // be available.
  155. Log.d(TAG, "onConnectionFailed:" + connectionResult);
  156. }
  157. private void showProgressDialog() {
  158. if (mProgressDialog == null) {
  159. mProgressDialog = new ProgressDialog(this);
  160. mProgressDialog.setMessage(getString(R.string.loading));
  161. mProgressDialog.setIndeterminate(true);
  162. }
  163. mProgressDialog.show();
  164. }
  165. private void hideProgressDialog() {
  166. if (mProgressDialog != null && mProgressDialog.isShowing()) {
  167. mProgressDialog.hide();
  168. }
  169. }
  170. private void updateUI(boolean isSignedIn) {
  171. if (isSignedIn) {
  172. btnSignIn.setVisibility(View.GONE);
  173. btnSignOut.setVisibility(View.VISIBLE);
  174. llProfileLayout.setVisibility(View.VISIBLE);
  175. } else {
  176. btnSignIn.setVisibility(View.VISIBLE);
  177. btnSignOut.setVisibility(View.GONE);
  178. llProfileLayout.setVisibility(View.GONE);
  179. }
  180. }
  181. }
Step 17
Just add the code to your build.gradle (code compile 'com.google.android.gmsplay-services9.6.1'). This code checks whether your mobile contains Google Play Service 9.6.1 above or not. If your Play Service version is below version 9.6.1, the app won’t run on your mobile.
android
Step 18
This is our user interface of the Application. Click Make project option.
android
Deliverables
Here, we successfully used Google authentication API in our Application, using an Android Studio Application and executed it.
Click Sign in button, followed by already signed Gmail id, which was shown. You just need to use it, else you can create mail id and sign in.
android
If you have any doubts, just comment.