In Focus

How To Use Google Authentication API In Your Application Using Android Studio

This article explains how to use Google Authentication API in your Application, using Android Studio

Introduction

Ninety percent of people use Android smart phones. 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

  • Android Studio. 
  • Stable internet connection.
  • Little bit XML and Java knowledge.

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. Afterwards, 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

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 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.   
  11.     <LinearLayout  
  12.         android:id="@+id/llProfile"  
  13.         android:layout_width="fill_parent"  
  14.         android:layout_height="wrap_content"  
  15.         android:layout_marginBottom="20dp"  
  16.         android:orientation="horizontal"  
  17.         android:visibility="gone"  
  18.         android:weightSum="3">  
  19.   
  20.         <ImageView  
  21.             android:id="@+id/imgProfilePic"  
  22.             android:layout_width="80dp"  
  23.             android:layout_height="wrap_content"  
  24.             android:layout_weight="1" />  
  25.   
  26.         <LinearLayout  
  27.             android:layout_width="wrap_content"  
  28.             android:layout_height="wrap_content"  
  29.             android:layout_marginLeft="10dp"  
  30.             android:layout_weight="2"  
  31.             android:orientation="vertical">  
  32.   
  33.             <TextView  
  34.                 android:id="@+id/txtName"  
  35.                 android:layout_width="wrap_content"  
  36.                 android:layout_height="wrap_content"  
  37.                 android:padding="5dp"  
  38.                 android:textSize="20dp" />  
  39.   
  40.             <TextView  
  41.                 android:id="@+id/txtEmail"  
  42.                 android:layout_width="wrap_content"  
  43.                 android:layout_height="wrap_content"  
  44.                 android:padding="5dp"  
  45.                 android:textSize="18dp" />  
  46.         </LinearLayout>  
  47.     </LinearLayout>  
  48.   
  49.     <com.google.android.gms.common.SignInButton  
  50.         android:id="@+id/btn_sign_in"  
  51.         android:layout_width="fill_parent"  
  52.         android:layout_height="wrap_content"  
  53.         android:layout_marginBottom="20dp" />  
  54.   
  55.     <Button  
  56.         android:id="@+id/btn_sign_out"  
  57.         android:layout_width="fill_parent"  
  58.         android:layout_height="wrap_content"  
  59.         android:layout_marginBottom="10dp"  
  60.         android:text="@string/btn_logout_from_google"  
  61.         android:visibility="gone" />  
  62.   
  63. </LinearLayout>   

Step 16

In MainActivity.java, copy and paste the code given below. Java programming is the backend language for an 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.   
  3. import android.app.ProgressDialog;  
  4. import android.content.Intent;  
  5. import android.os.Bundle;  
  6. import android.support.annotation.NonNull;  
  7. import android.support.v7.app.AppCompatActivity;  
  8. import android.util.Log;  
  9. import android.view.View;  
  10. import android.widget.Button;  
  11. import android.widget.ImageView;  
  12. import android.widget.LinearLayout;  
  13. import android.widget.TextView;  
  14.   
  15. import com.bumptech.glide.Glide;  
  16. import com.bumptech.glide.load.engine.DiskCacheStrategy;  
  17. import com.google.android.gms.auth.api.Auth;  
  18. import com.google.android.gms.auth.api.signin.GoogleSignInAccount;  
  19. import com.google.android.gms.auth.api.signin.GoogleSignInOptions;  
  20. import com.google.android.gms.auth.api.signin.GoogleSignInResult;  
  21. import com.google.android.gms.common.ConnectionResult;  
  22. import com.google.android.gms.common.SignInButton;  
  23. import com.google.android.gms.common.api.GoogleApiClient;  
  24. import com.google.android.gms.common.api.OptionalPendingResult;  
  25. import com.google.android.gms.common.api.ResultCallback;  
  26. import com.google.android.gms.common.api.Status;  
  27.   
  28. public class MainActivity extends AppCompatActivity implements View.OnClickListener, GoogleApiClient.OnConnectionFailedListener {  
  29.     private static final String TAG = MainActivity.class.getSimpleName();  
  30.     private static final int RC_SIGN_IN = 420;  
  31.   
  32.     private GoogleApiClient mGoogleApiClient;  
  33.     private ProgressDialog mProgressDialog;  
  34.   
  35.     private SignInButton btnSignIn;  
  36.     private Button btnSignOut;  
  37.     private LinearLayout llProfileLayout;  
  38.     private ImageView imgProfilePic;  
  39.     private TextView txtName, txtEmail;  
  40.   
  41.     @Override  
  42.     protected void onCreate(Bundle savedInstanceState) {  
  43.         super.onCreate(savedInstanceState);  
  44.         setContentView(R.layout.activity_main);  
  45.         initializeControls();  
  46.         initializeGPlusSettings();  
  47.     }  
  48.   
  49.     private void initializeControls(){  
  50.         btnSignIn = (SignInButton) findViewById(R.id.btn_sign_in);  
  51.         btnSignOut = (Button) findViewById(R.id.btn_sign_out);  
  52.         llProfileLayout = (LinearLayout) findViewById(R.id.llProfile);  
  53.         imgProfilePic = (ImageView) findViewById(R.id.imgProfilePic);  
  54.         txtName = (TextView) findViewById(R.id.txtName);  
  55.         txtEmail = (TextView) findViewById(R.id.txtEmail);  
  56.   
  57.         btnSignIn.setOnClickListener(this);  
  58.         btnSignOut.setOnClickListener(this);  
  59.     }  
  60.   
  61.     private void initializeGPlusSettings(){  
  62.         GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)  
  63.                 .requestEmail()  
  64.                 .build();  
  65.   
  66.         mGoogleApiClient = new GoogleApiClient.Builder(this)  
  67.                 .enableAutoManage(thisthis)  
  68.                 .addApi(Auth.GOOGLE_SIGN_IN_API, gso)  
  69.                 .build();  
  70.   
  71.         // Customizing G+ button  
  72.         btnSignIn.setSize(SignInButton.SIZE_STANDARD);  
  73.         btnSignIn.setScopes(gso.getScopeArray());  
  74.     }  
  75.   
  76.   
  77.     private void signIn() {  
  78.         Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);  
  79.         startActivityForResult(signInIntent, RC_SIGN_IN);  
  80.     }  
  81.   
  82.   
  83.     private void signOut() {  
  84.         Auth.GoogleSignInApi.signOut(mGoogleApiClient).setResultCallback(  
  85.                 new ResultCallback<Status>() {  
  86.                     @Override  
  87.                     public void onResult(Status status) {  
  88.                         updateUI(false);  
  89.                     }  
  90.                 });  
  91.     }  
  92.   
  93.     private void handleGPlusSignInResult(GoogleSignInResult result) {  
  94.         Log.d(TAG, "handleSignInResult:" + result.isSuccess());  
  95.         if (result.isSuccess()) {  
  96.             // Signed in successfully, show authenticated UI.  
  97.             GoogleSignInAccount acct = result.getSignInAccount();  
  98.   
  99.             //Fetch values  
  100.             String personName = acct.getDisplayName();  
  101.             String personPhotoUrl = acct.getPhotoUrl().toString();  
  102.             String email = acct.getEmail();  
  103.             String familyName = acct.getFamilyName();  
  104.   
  105.             Log.e(TAG, "Name: " + personName +  
  106.                     ", email: " + email +  
  107.                     ", Image: " + personPhotoUrl +  
  108.                     ", Family Name: " + familyName);  
  109.   
  110.             //Set values  
  111.             txtName.setText(personName);  
  112.             txtEmail.setText(email);  
  113.   
  114.             //Set profile pic with the help of Glide  
  115.             Glide.with(getApplicationContext()).load(personPhotoUrl)  
  116.                     .thumbnail(0.5f)  
  117.                     .crossFade()  
  118.                     .diskCacheStrategy(DiskCacheStrategy.ALL)  
  119.                     .into(imgProfilePic);  
  120.   
  121.             updateUI(true);  
  122.         } else {  
  123.             // Signed out, show unauthenticated UI.  
  124.             updateUI(false);  
  125.         }  
  126.     }  
  127.   
  128.     @Override  
  129.     public void onClick(View v) {  
  130.         int id = v.getId();  
  131.         switch (id) {  
  132.             case R.id.btn_sign_in:  
  133.                 signIn();  
  134.                 break;  
  135.             case R.id.btn_sign_out:  
  136.                 signOut();  
  137.                 break;  
  138.         }  
  139.     }  
  140.   
  141.     @Override  
  142.     public void onActivityResult(int requestCode, int resultCode, Intent data) {  
  143.         super.onActivityResult(requestCode, resultCode, data);  
  144.   
  145.         // Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...);  
  146.         if (requestCode == RC_SIGN_IN) {  
  147.             GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);  
  148.             handleGPlusSignInResult(result);  
  149.         }  
  150.     }  
  151.   
  152.     @Override  
  153.     public void onStart() {  
  154.         super.onStart();  
  155.   
  156.         OptionalPendingResult<GoogleSignInResult> opr = Auth.GoogleSignInApi.silentSignIn(mGoogleApiClient);  
  157.         if (opr.isDone()) {  
  158.             // If the user's cached credentials are valid, the OptionalPendingResult will be "done"  
  159.             // and the GoogleSignInResult will be available instantly.  
  160.             Log.d(TAG, "Got cached sign-in");  
  161.             GoogleSignInResult result = opr.get();  
  162.             handleGPlusSignInResult(result);  
  163.         } else {  
  164.             // If the user has not previously signed in on this device or the sign-in has expired,  
  165.             // this asynchronous branch will attempt to sign in the user silently.  Cross-device  
  166.             // single sign-on will occur in this branch.  
  167.             showProgressDialog();  
  168.             opr.setResultCallback(new ResultCallback<GoogleSignInResult>() {  
  169.                 @Override  
  170.                 public void onResult(GoogleSignInResult googleSignInResult) {  
  171.                     hideProgressDialog();  
  172.                     handleGPlusSignInResult(googleSignInResult);  
  173.                 }  
  174.             });  
  175.         }  
  176.     }  
  177.   
  178.     @Override  
  179.     public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {  
  180.         // An unresolvable error has occurred and Google APIs (including Sign-In) will not  
  181.         // be available.  
  182.         Log.d(TAG, "onConnectionFailed:" + connectionResult);  
  183.     }  
  184.   
  185.     private void showProgressDialog() {  
  186.         if (mProgressDialog == null) {  
  187.             mProgressDialog = new ProgressDialog(this);  
  188.             mProgressDialog.setMessage(getString(R.string.loading));  
  189.             mProgressDialog.setIndeterminate(true);  
  190.         }  
  191.   
  192.         mProgressDialog.show();  
  193.     }  
  194.   
  195.     private void hideProgressDialog() {  
  196.         if (mProgressDialog != null && mProgressDialog.isShowing()) {  
  197.             mProgressDialog.hide();  
  198.         }  
  199.     }  
  200.   
  201.     private void updateUI(boolean isSignedIn) {  
  202.         if (isSignedIn) {  
  203.             btnSignIn.setVisibility(View.GONE);  
  204.             btnSignOut.setVisibility(View.VISIBLE);  
  205.             llProfileLayout.setVisibility(View.VISIBLE);  
  206.         } else {  
  207.             btnSignIn.setVisibility(View.VISIBLE);  
  208.             btnSignOut.setVisibility(View.GONE);  
  209.             llProfileLayout.setVisibility(View.GONE);  
  210.         }  
  211.     }  
  212.    
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.