How to Sign in with Google in Android Tutorial

In this tutorial, we are going to explain how to sign in with Google in Android Application.

Don't Miss

Many apps want to establish the user’s Identity so as to customize the app to the user’s needs, save their information, allow them to identify themselves in social circles and countless other scenarios. There are some ways that you can allow your users to identify themselves, such as implementing a sign in functionality of your own, the place you handle your users and their credentials, or, as is becoming more and more extra frequent, you’ll be able to allow them to sign in using their credentials from generally used platforms such as Facebook, Twitter or Google.

To support this, we’ve built the Google Identity Platform and the services it provides, including Google Sign-In for Android, iOS and the Web, the Google Identity Toolkit, that allows you to integrate multiple identity providers, plain OAuth 2.zero for typical check in situations, and the Chrome Identity API which permits customers to signal into your Chrome Apps.

In this tutorial, you’ll learn how to provide sign-in functionality to your Android App, built using Android Studio, using Google Sign-In.

Google Sign-In is a technology that allows you to get users into your apps shortly and securely with little development work required. It allows you to create a seamless experience across screens to your users — they sign in as soon as, and are authenticated on your whole devices. It allows you to combine Google’s services into your web sites and mobile apps, and likewise enables over-the-air installation of Android apps when users sign into your websites. In this lesson you’ll learn how to add Google Sign-In to your android app — and manage the workflow of your users signing into your app.

Enabling Sign-In for Android Application

Before you begin coding any of the Android functionality, it is advisable activate the Sign-In APIs for your Android application in the Google Developer’s console. 

Create a Project

To create a project, go to the developer’s console at: https://console.developers.google.com/project.

We need to create a project on Google Developer Console so, press the ‘Create Project’

Enter a significant name on your project within the ‘Project name’ field. For the project ID, you’ll need to enter one thing that’s distinctive across all of Google’s infrastructure.  

Enable the Google+ API

Go to Google API+ library. Click on the Enable button to access Google+ library.

Configure Credentials

In this step you’ll configure the credentials for your application. Google uses this to ensure that your application isn’t a fake application attempting to use our infrastructure. Follow below steps:

  • Go to Dashboard link
  • Select Your project as below image, we choosed Google Sign in project
  • Click on the CREATE CREDENTIALS and choose API key
  • Rename Your API Key
  • Choose Android Apps in the Application restrictions section.
  • Generate SHA Key from your terminal. Use the below code to generate fingerprint.
    • Debug certificate fingerprint
      • For Linux or macOS: keytool -list -v -keystore ~/.android/debug.keystore -alias androiddebugkey -storepass android -keypass android
      • For Windows: keytool -list -v -keystore “%USERPROFILE%\.android\debug.keystore” -alias androiddebugkey -storepass android -keypass android
    • Release certificate fingerprint
      • keytool -list -v -keystore your_keystore_name -alias your_alias_name
  • Click on the ADD AN ITEM button in the Restrict usage to your Android apps section. Add your project Package Name & SHA 1 in the provided field.

Configure your 0Auth Consent Screen

You’ll see a display where you specify details about your product to form a consent screen. You should present your e-mail address and Product name. Everything else is non-compulsory. An example of a consent screen is proven on the correct hand side. You’re in all probability familiar with seeing these if you’ve run any Android apps in your phone that require user permissions, and signin is no exception.

Add Dependency

Add below dependency in your build.gradle file:

dependencies {
....
    implementation 'com.google.android.gms:play-services:7.3.0'
}

Configure AndroidManifest.xml

In the manifests folder, find and open your AndroidManifest.xml. Add the following code:

<meta-data
    android:name="com.google.android.gms.version"
    android:value="@integer/google_play_services_version" />

The value field references a resource that’s contained throughout the Google Play Services client library you added as a dependency earlier.  This tells the manifest which version of Google Play Services you count on so that you just app will run properly on as many devices as possible.

Finally, add the following lines above the <application> tag and inside <manifest>:

   <uses-permission android:name="android.permission.INTERNET" />
   <uses-permission android:name="android.permission.GET_ACCOUNTS" />
   <uses-permission android:name="android.permission.USE_CREDENTIALS" />

Layout Design

Add the under layout design in your activity.xml file. This structure provides you a Sign-In button, and a few buttons for signing out and revoking  access. It also offers a TextView where the status of the sign in process can be displayed.

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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=".MainActivity">

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:padding="2dip"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintTop_toTopOf="parent" >
        
        <com.google.android.gms.common.SignInButton
            android:id="@+id/sign_in_button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:enabled="false" />

        <Button
            android:id="@+id/sign_out_button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Sign Out"
            android:enabled="true" />

        <Button
            android:id="@+id/revoke_access_button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Revoke Access"
            android:enabled="true" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/statuslabel"
            android:text="Status"/>
    </LinearLayout>

</androidx.constraintlayout.widget.ConstraintLayout>
Google Sign In Android

Implements ConnectionCallbacks, OnConnectionFailedListener, View.OnClickListener

Now, we need to implement ConnectionCallbacks, OnConnectionFailedListener, View.OnClickListener. in the activity file. Add the following code:

public class MainActivity extends AppCompatActivity implements
        ConnectionCallbacks, OnConnectionFailedListener,
        View.OnClickListener {

Implement Constants and Class Variables

As you write the code there are a selection of variables and constants which are shared throughout various functions. Put all of those below the MainActivity declaration, however earlier than the first function (which is probably going the OnCreate one).

First are the constants. Just declare these for now. You’ll see what each does when you use them.

private static final int SIGNED_IN = 0;
private static final int STATE_SIGNING_IN = 1;
private static final int STATE_IN_PROGRESS = 2;
private static final int RC_SIGN_IN = 0;

Next are some variables that can represent various objects or information that you’ll need. Again, you’ll see what every of those does when you’re using them. 

private GoogleApiClient mGoogleApiClient;
private int mSignInProgress;
private PendingIntent mSignInIntent;

Finally add the declarations for the controls on the User Interface.

private SignInButton mSignInButton;
private Button mSignOutButton;
private Button mRevokeButton;
private TextView mStatus;

Implement OnCreate()

When Android begins your app, and prompts your activity, the OnCreate() method fires because the working system ‘creates’ the activity. Code inside your OnCreate() perform will then execute.

At the second, your onCreate code appears like this:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}

Replace it with the following code.  This code will link your MainActivity java code to the UI you created earlier and also initiate the GoogleApiClient which you will use to control sign-in.

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Get references to all of the UI views
        mSignInButton = (SignInButton) findViewById(R.id.sign_in_button);
        mSignOutButton = (Button) findViewById(R.id.sign_out_button);
        mRevokeButton = (Button) findViewById(R.id.revoke_access_button);
        mStatus = (TextView) findViewById(R.id.statuslabel);

        // Add click listeners for the buttons
   mSignInButton.setOnClickListener(this);
   mSignOutButton.setOnClickListener(this);
   mRevokeButton.setOnClickListener(this);

   // Build a GoogleApiClient
   mGoogleApiClient = buildGoogleApiClient();
    }

You might discover that buildGoogleApiClient is displaying as an error — that’s as a result of we haven’t created it ye!. You’ll do this within the subsequent step.  The GoogleApiClient class his is the principle entry level for Google Play providers purposes, you will discover detailed documentation on it here. You might be implementing buildGoogleApiClient() within the next step.

Build the Api Client

In the earlier part, in addition to setting up the UI controls, you additionally assigned your GoogleApiClient to the outcomes of a perform referred to as buildGoogleApiClient(). You hadn’t created this perform but, so that you’ll do this on this step.

The Google Api Client is the main entry point to Google Play services. To create one, it’s essential specify quite a few issues:

  • Location of Connection Callbacks. The Google Api Client is highly asynchronous in nature, and wishes features carried out someplace that it calls when it’s linked (onConnected) and when the connection is suspended (onConnectionSuspended). In this lab you’ll code these on this activity, so that you set the location for the connection callbacks to this.
  • Location of Connection Failed callback. It additionally wants you to specify the location of the onConnectedFailed function which runs if there’s a failure within the connection
  • The APIs that you just need to use. Google Play providers helps lots of APIs, so that you specify which of them you need to hook up with right here.
  • In the case of logging in, you additionally specify the Login Scope. This defines the quantity of details about the user that your app will access. Details on scopes might be found here. You’ll be using e-mail scope on this tutorial — which only offers access to the user’s e-mail address for identification moderately than their full Google+ profile.

Add the buildGoogleApiClient() method to MainActivity. The full definition is:

private GoogleApiClient buildGoogleApiClient() {
        return new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(Plus.API, Plus.PlusOptions.builder().build())
                .addScope(new Scope("email"))
                .build();
    }

Implement onStart() and onStop()

When your activity begins is the ideal time to attach the Google API Client to Google Play services. Similarly, when it stops is the best time to disconnect it.

Override the onStart() and onStop() methods to do exactly that with the following code:

@Override
protected void onStart() {
    super.onStart();
    mGoogleApiClient.connect();
}

@Override
protected void onStop() {
    super.onStop();
    mGoogleApiClient.disconnect();
}

Handle Suspended scenarios

Occasionally the connection to Google Play services can drop out. It doesn’t disconnect, however will get lost for some motive. If this occurs, one of the best factor to do is to attempt to reconnect.

Add the onConnectionSuspended() method:

@Override
public void onConnectionSuspended(int cause) {
    mGoogleApiClient.connect();
}

Handle Connection to Google Play services.

When using Google Play services with signin — the second the app connects to the services is the moment the user is signed in. When the onConnected() callback executes, the user is linked. For this lab, you’ll allow the buttons, and get some particulars concerning the user. Remember you might be using e-mail scope which only offers access to their e-mail deal with, so we’ll get that. If you attempt to get different details about the user (for example, their circle of Google+ friends), you’ll get an exception.

Add the onConnected() method to MainActivity:

@Override
public void onConnected(Bundle connectionHint) {
    mSignInButton.setEnabled(false);
    mSignOutButton.setEnabled(true);
    mRevokeButton.setEnabled(true);

    // Indicate that the sign in process is complete.
    mSignInProgress = SIGNED_IN;

    try {
        String emailAddress = Plus.AccountApi.getAccountName(mGoogleApiClient);
        mStatus.setText(String.format("Signed In to My App as %s", emailAddress));
    }
    catch(Exception ex){
        String exception = ex.getLocalizedMessage();
        String exceptionString = ex.toString();
        // Note that you should log these errors in a 'real' app to aid in debugging
    }
}

Note that we set the mSignInProgress to STATE_SIGNED_IN. This is used by the app to trace the status of signing in. You’ll see how that’s used within the next step.

Handle Connection Failures

Signing in with Google is just a little distinctive on the subject of connection failures. Typically a connection failure to Google Play services occurs since you don’t have connectivity, however when using signin, it can extra frequently occur as a result of the person is in a transitional state, the place they aren’t totally signed in but. There could also be two intermediate steps, and when the user hasn’t completed them, Google Play services returns a connection failure.

The first of those two steps happens when the user has a couple of Google account registered on the device. Android will show them a dialog asking which account it ought to use. At this level, your connection has failed.

The second of those steps occurs when the app reveals a dialog to the user asking if they are going to give permissions to the app to entry info based mostly on the required scope.

As a developer, you deal with this as connection failures in onConnectionFailed, and also you repeatedly attempt to reconnect. This is the place the mSignInProgress and the various constants you defined earlier STATE_DEFAULTSTATE_SIGNED_IN and STATE_IN_PROGRESS are used.

Add the onConnectionFailed() and resolveSignInError() methods to MainActivity. Here’s the code:

@Override
    public void onConnectionFailed(ConnectionResult result) {
        if (mSignInProgress != STATE_IN_PROGRESS) {
            mSignInIntent = result.getResolution();
            if (mSignInProgress == STATE_SIGNING_IN) {
                resolveSignInError();
            }
        }
        // Will implement shortly
        onSignedOut();
    }

    private void resolveSignInError() {
        if (mSignInIntent != null) {
            try {
                mSignInProgress = STATE_IN_PROGRESS;
                startIntentSenderForResult(mSignInIntent.getIntentSender(),
                        RC_SIGN_IN, null, 0, 0, 0);
            } catch (IntentSender.SendIntentException e) {
                mSignInProgress = STATE_SIGNING_IN;
                mGoogleApiClient.connect();
            }
        } else {
            // You have a play services error -- inform the user
        }
    }

The onConnectionFailed() method checks to see if the sign in process remains to be in progress, and whether it is, it will get the intent that was returned by the callback. This intent will represent the dialog asking the user to sign in, or that asking the user for his or her permissions. If that is the case, the resolveSignInError() method is named. This checks the intent, and flags that the register remains to be in progress. The person’s response with the intents can be handled in onActivityResult().

Add the onActivityResult() method to MainActivity. Here’s the code:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case RC_SIGN_IN:
                if (resultCode == RESULT_OK) {
                    mSignInProgress = STATE_SIGNING_IN;
                } else {
                    mSignInProgress = SIGNED_IN;
                }

                if (!mGoogleApiClient.isConnecting()) {
                    mGoogleApiClient.connect();
                }
                break;
}
}

As the user resolves the intents by answering the dialogs introduced, the circulate will finally result in a connection to the API (if their credentials are correct) or a ‘real’ failure (in the event that they aren’t). Should we attain the latter — the onSignedOut() function (in onConnectionFailed) might be referred to as. You’ll implement that next.

Implement onSignedOut()

When the user signs out, or if their sign in fails for some reason, your app must to update the UI, disabling the sign out and revoke entry buttons, and enabling the login button in order that they’ll the user can once more.

Add the onSignedOut() method to MainActivity. Here’s the code:

private void onSignedOut() {
        // Update the UI to reflect that the user is signed out.
        mSignInButton.setEnabled(true);
        mSignOutButton.setEnabled(false);
        mRevokeButton.setEnabled(false);

        mStatus.setText("Signed out");
    }

Implement the onClick handlers

The final step is to implement the click handlers for the three buttons. Earlier (in onCreate()) you specified that this activity would contain them, so you can achieve this by implementing an onClick override in this activity, and checking which UI element (a View in this case) triggered the callback.

Add the code to MainActivity to define the onClick behavior for the buttons. Here’s the code:

@Override
    public void onClick(View v) {
        if (!mGoogleApiClient.isConnecting()) {
            switch (v.getId()) {
                case R.id.sign_in_button:
                    mStatus.setText("Signing In");
                    resolveSignInError();
                    break;
                case R.id.sign_out_button:
                    Plus.AccountApi.clearDefaultAccount(mGoogleApiClient);
                    mGoogleApiClient.disconnect();
                    mGoogleApiClient.connect();
                    break;
                case R.id.revoke_access_button:
                    Plus.AccountApi.clearDefaultAccount(mGoogleApiClient);
                    Plus.AccountApi.revokeAccessAndDisconnect(mGoogleApiClient);
                    mGoogleApiClient = buildGoogleApiClient();
                    mGoogleApiClient.connect();
                    break;
            }
        }
    }

This code will ignore any button clicks if the GoogleApiClient is within the strategy of connecting. Otherwise, for the sign in Button, it can change the status text to Signing In, and enter the decision of Sign In errors. Remember that if Android reveals the ‘pick which email address’ or the permissions dialog, these might be handled as ‘errors’.

For the sign out button, the default account might be cleared, in order that on next sign in the user might be given a choice of which ID to make use of when signing in. Also, the client will disconnect and reconnect.

Finally, for revoking access, the user might be signed out, and entry that they gave to the profile might be revoked. In different words, if the user signs in, and gives permission to the e-mail profile, and then indicators out, then on further sign in, they shouldn’t want to give the same permissions. However, in the event that they revoke access, then on future sign-ins, they’d have to present access once more so as to be able to sign into the application.

That’s it. You’re now able to run and check out your app!

LEAVE A REPLY

Please enter your comment!
Please enter your name here

564FansLike

Recent Posts

Concept of Session in Laravel Tutorial

Sessions are used to store details about the user throughout the requests. Laravel supplies various drivers like file, cookie, apc, array, Memcached, Redis, and database to handle session data. By default, file driver is used as a result of it's light-weight....

Laravel Url Generation Tutorial

Our web application revolves around routes and URLs. After all, they're what direct our users to our pages. At the end of the day, serving pages is what any web application should do. Our users may...

Concept of Laravel Views Tutorial

In MVC framework, the letter "V" stands for Views. It separates the application logic and presentation logic. Views are saved in resources/views listing. Generally, the view contains the HTML which might be served by the application.

Related Articles

Concept of Session in Laravel Tutorial

Sessions are used to store details about the user throughout the requests. Laravel supplies various drivers like file, cookie, apc, array, Memcached, Redis, and database to handle session data. By default, file driver is used as a result of it's light-weight....

Laravel Url Generation Tutorial

Our web application revolves around routes and URLs. After all, they're what direct our users to our pages. At the end of the day, serving pages is what any web application should do. Our users may...

Concept of Laravel Views Tutorial

In MVC framework, the letter "V" stands for Views. It separates the application logic and presentation logic. Views are saved in resources/views listing. Generally, the view contains the HTML which might be served by the application.
WP2Social Auto Publish Powered By : XYZScripts.com