Android

Google Identity Sign in With Google

android sign in with google
Written by Yasir Ameen

In most cases we let our android app to Sign in with google for getting more engaging experience. Using the google API(s) you can achieve this functionality in your app.

There are two main steps you will see in detail in order to implement Sign in with google in your android App.

  1. Configure a Google developer console project
  2. Set up Android Studio Project

 

Following dependencies i am using in this project

 dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.3.0'
    compile 'com.google.android.gms:play-services-auth:8.3.0'
    compile 'com.pkmmte.view:circularimageview:1.1'
    compile 'com.squareup.picasso:picasso:2.5.2'

}

 

Configure a Google Developer Console Project

You must configure Google Developer Console Project before start integrating Google Sign-in. You can configure Google Developer Console Project by following me , you must be sign-in with google account to configure project.

Step 1) Google Developer Console Project Link

Go to the following link Google Developer Console and Generate Configuration File you will see following page, just enter your Google Developer Console Project name and enter any package name you want also choose your country and click Continue to Choose and configure service Button.

android generating configuration file

 

Step 2) Choosing Service And Getting SHA-1

on the second page you will see following screen with a message in green text at the top with Google Sign-In service selected by default, also we need a SHA-1 signing certificate in order to create OAuth2 client and API key for our app.

google developer choosing a service

 

Retrieving SHA-1 Signin Certificate

In order to retrieve SHA-1, open command prompt and goto the C:\Program Files\Java\jdk1.8.0_60\bin and type the following

sha-1 signin certificateand hit enter, you will set generated details below.

android sha-1 signin certificate

 

after typing the above command in command prompt, you will see the above details, just copy the SHA-1 and paste it into Android Signing Certification SHA-1 field and click ENABLE GOOGLE SIGN-IN button and also click Continue to Generate Configuration files from the next page you see.

 

android enabling google signin

Step 3) Downloading Configuration File

You have successfully configure your Google Console Project, Now download google-service.json file simply clicking the Download Google-Service.json button.

 

Downloading Google Service File

Downloaded file google-service.json contains project number, project id client id, api key and others information, you see the content of configuration file i download for the educational purpose.

{
  "project_info": {
    "project_number": "918417143594",
    "project_id": "deductive-torus-130523"
  },
  "client": [
    {
      "client_info": {
        "mobilesdk_app_id": "1:918417143594:android:09187d70352e8073",
        "android_client_info": {
          "package_name": "com.yasir.identitygoogle"
        }
      },
      "oauth_client": [
        {
          "client_id": "918417143594-k0cul3u2b348pkq5dl6vckslu0j7u12v.apps.googleusercontent.com",
          "client_type": 1,
          "android_info": {
            "package_name": "com.yasirameen.identity",
            "certificate_hash": "05A77636B0C7CD8F3D982AAA4A977EBA378C9141"
          }
        },
        {
          "client_id": "918417143594-vm5ujajfa5rff9q3kchkmipi28j11iqm.apps.googleusercontent.com",
          "client_type": 3
        }
      ],
      "api_key": [
        {
          "current_key": "AIzaSyB0iAh-f6vRC3UVpYORbtu8yAczvEw-0NA"
        }
      ],
      "services": {
        "analytics_service": {
          "status": 1
        },
        "appinvite_service": {
          "status": 1,
          "other_platform_oauth_client": []
        },
        "ads_service": {
          "status": 1
        }
      }
    }
  ],
  "configuration_version": "1"
}

 

 

Set up Android Studio Project

This is the second part of the Sign-in with google identity, all you need to is to create a project in Android Studio and name it Google Identity or else, make sure package name of your project must be match with Google Console Project you created, in my case i entered package name => com.yasirameen.identity

 

Step 1) Adding Configuration File To Your Project

Copy the google-service.json  file you just downloaded into the app/ directory of your Android Studio project. The Google plugin for Gradle parses configuration information from the google-service.json file.

 

Step 2) Adding Google Service Plugin

a) Open your build.gradle(project:GoogleIdentity)  and paste the following following dependency

classpath 'com.google.gms:google-services:2.0.0-alpha5'

android google service classpath

b) Open your build.gradle(Modul:app) and the paste the following plugin

apply plugin: 'com.google.gms.google-services'

adding google service plugin

 

Starting Integrating Sign In With Google

Now you have setup your Google Console Project and you have also setup Android Studio Project now its time to implement all together, but first let’s create  the design for your SignInActivity(MainActivity).

Google Sign In Button.

Google provides their own button design for Sign In, you can create this button by writing following code in your xml, also you can change its appearance, will see later.

   <com.google.android.gms.common.SignInButton
    android:id="@+id/sign_in_button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

android google sign in button

Let’s Create Layout For Sign In With Google Activity

Open acitivity_main.xml from the res=>layout directory and paste following xml code


<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity">

    <com.google.android.gms.common.SignInButton
        android:id="@+id/sign_in_button"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:layout_marginLeft="60dp"
        android:layout_marginTop="61dp"
        android:layout_below="@+id/textView2"
        android:layout_centerHorizontal="true" />

    <ImageView
        android:layout_width="80dp"
        android:layout_height="80dp"
        android:id="@+id/imageView"
        android:src="@drawable/google_icon"
        android:layout_marginTop="79dp"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true" />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="Google Identitty"
        android:textSize="32sp"
        android:gravity="center"
        android:id="@+id/textView"
        android:layout_marginTop="14dp"
        android:layout_below="@+id/imageView"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceSmall"
        android:text="Android Sign in With Google"
        android:id="@+id/textView2"
        android:textSize="16sp"
        android:gravity="center"
        android:layout_below="@+id/textView"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceSmall"
        android:text="Android | Lollipop | Material | Yasir | Ameen | Signin | Google |  Design | Activity | Blog | Facebook | Kitkat | Marshmallow | Google | Identity"
        android:textColor="#000000"
        android:alpha="0.6"
        android:id="@+id/textView4"
        android:gravity="center_horizontal"
        android:layout_marginBottom="52dp"
        android:layout_alignParentBottom="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true" />

</RelativeLayout>

you will see following output, you can download google logo from google 🙂

 

android sign in with google layout

 Writing Functionality of Sign In With Google Activity

Open MainActivity.java and setup your class look like below.

public class MainActivity extends AppCompatActivity implements GoogleApiClient.OnConnectionFailedListener {


    private static final String TAG = "MainActivity";
    private static final int SIGN_IN = 001;
    private GoogleApiClient mGoogleApiClient;
    SignInButton signInButton;

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


   }

@Override
public void onConnectionFailed(ConnectionResult connectionResult) {

  }
} 

In onCreate method of SignInActivity(MainActivity), request the user data by configuring Google Sign-In required by your app and accessing Google Sign in Api, just copy and paste the following snippet in onCreate method.

 


//ID, email address and basic profile are included in DEFAULT_SING_IN. 
GoogleSignInOptions googleSignInOptions = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
        .requestEmail()
        .build();


//Building a GoogleApiClient with access to the Google Sign-in API and options
//specified by googleSignInOptions 
mGoogleApiClient = new GoogleApiClient.Builder(this)
        .enableAutoManage(this,this)
        .addApi(Auth.GOOGLE_SIGN_IN_API, googleSignInOptions)
        .build();

//Customizing Sign In With Google Button
signInButton = (SignInButton) findViewById(R.id.sign_in_button);
signInButton.setSize(SignInButton.SIZE_WIDE);
signInButton.setColorScheme(SignInButton.COLOR_DARK);
signInButton.setScopes(googleSignInOptions.getScopeArray());

Putting It All Together

Here is the complete code of MainActivity , just copy the following code and paste it. Also create another Empty Activity and call it DashboardActivity for showing results.


 public class MainActivity extends AppCompatActivity implements GoogleApiClient.OnConnectionFailedListener {


    private static final String TAG = "MainActivity";
    private static final int SIGN_IN = 001;

    private GoogleApiClient mGoogleApiClient;
    private ProgressDialog progressDialog;
    SignInButton signInButton;

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





        //ID, email address and basic profile are included in DEFAULT_SING_IN.
        GoogleSignInOptions googleSignInOptions = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                .requestEmail()
                .build();


        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .enableAutoManage(this,this)
                .addApi(Auth.GOOGLE_SIGN_IN_API, googleSignInOptions)
                .build();

        signInButton = (SignInButton) findViewById(R.id.sign_in_button);
        signInButton.setSize(SignInButton.SIZE_WIDE);
        signInButton.setColorScheme(SignInButton.COLOR_DARK);
        signInButton.setScopes(googleSignInOptions.getScopeArray());




        signInButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
                startActivityForResult(signInIntent, SIGN_IN);
            }
        });

    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        // Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...);
        if (requestCode == SIGN_IN) {
            GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
            handleSignInResult(result);

        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        OptionalPendingResult<GoogleSignInResult> opr = Auth.GoogleSignInApi.silentSignIn(mGoogleApiClient);
        if (opr.isDone()) {
            // If the user's cached credentials are valid, the OptionalPendingResult will be "done"
            // and the GoogleSignInResult will be available instantly.
            Log.d(TAG, "Got cached sign-in");
            GoogleSignInResult result = opr.get();
            handleSignInResult(result);
        } else {
            // If the user has not previously signed in on this device or the sign-in has expired,
            // this asynchronous branch will attempt to sign in the user silently.  Cross-device
            // single sign-on will occur in this branch.
            showProgressDialog();
            opr.setResultCallback(new ResultCallback<GoogleSignInResult>() {
                @Override
                public void onResult(GoogleSignInResult googleSignInResult) {
                    hideProgressDialog();
                    handleSignInResult(googleSignInResult);
                }
            });
        }
    }


    private void handleSignInResult(GoogleSignInResult result) {
        Log.d(TAG, "handleSignInResult:" + result.isSuccess());
        if (result.isSuccess()) {


            // Signed in successfully, show authenticated UI.
            GoogleSignInAccount acct = result.getSignInAccount();
            String accountName = acct.getDisplayName();
            String accountEmail = acct.getEmail();
            Uri accountPic = acct.getPhotoUrl();
            Intent intent = new Intent(MainActivity.this,DashboardActivity.class);
            intent.putExtra("name",accountName);
            intent.putExtra("email",accountEmail);
            intent.putExtra("pic",accountPic.toString());
            startActivity(intent);
            finish();


        } else {

        }
    }

    private void showProgressDialog() {
        if (progressDialog == null) {
            progressDialog = new ProgressDialog(this);
            progressDialog.setTitle("Please Wait");
            progressDialog.setMessage("Loading....");
            progressDialog.setIcon(R.drawable.google);
            progressDialog.setIndeterminate(true);
            progressDialog.setCancelable(false);
        }

        progressDialog.show();
    }

    private void hideProgressDialog() {
        if (progressDialog != null && progressDialog.isShowing()) {
            progressDialog.hide();
        }
    }

    
    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {

        Toast.makeText(MainActivity.this, connectionResult.getErrorMessage(), Toast.LENGTH_SHORT).show();
    }
}

Creating Dashboard Activity

Create empty Activity and name it DashboardActivity, we will use dashboard activity after successfully Sign In with Google. just open activity_dashboard.xml and paste the following xml code.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.yasir.identitygoogle.DashboardActivity">

    <com.pkmmte.view.CircularImageView
        android:layout_width="75dp"
        android:layout_height="75dp"
        android:scaleType="centerCrop"
        app:border_color="#ffffff"
        app:shadow="true"
        android:id="@+id/account_image"
        android:layout_marginTop="86dp"
        android:layout_below="@+id/textView5"
        android:layout_centerHorizontal="true" />


    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="Welcome, Sign In User!"
        android:id="@+id/account_title"
        android:paddingLeft="10dp"
        android:textColor="#000000"
        android:gravity="center"
        android:textSize="22sp"
        android:layout_below="@+id/account_image"
        android:layout_centerHorizontal="true" />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceSmall"
        android:text=" SignInUser@GMAIL.COM"
        android:textColor="#000000"
        android:textSize="14sp"
        android:gravity="center"
        android:paddingLeft="10dp"
        android:id="@+id/account_email"
        android:layout_below="@+id/account_image"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="28dp" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:paddingLeft="10dp"
        android:paddingRight="10dp"
        android:id="@+id/linearLayout"
        android:layout_marginTop="113dp"
        android:layout_below="@+id/account_email"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true">

        <Button
            android:id="@+id/signout"
            android:layout_weight="1.28"
            android:layout_width="wrap_content"
            android:layout_height="40dp"
            android:textColor="#ffffff"
            android:background="#03A9F4"
            android:textAllCaps="false"
            android:text="Sign Out"/>

        <Button
            android:id="@+id/revoke"
            android:layout_weight="1"
            android:layout_width="wrap_content"
            android:layout_height="40dp"
            android:textColor="#ffffff"
            android:layout_marginLeft="2dp"
            android:background="#03A9F4"
            android:textAllCaps="false"
            android:text="Revoke Access"/>

    </LinearLayout>


    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="Google Identity"
        android:textSize="32sp"
        android:gravity="center"
        android:id="@+id/textView3"
        android:layout_below="@+id/imageView2"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_marginTop="11dp" />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceSmall"
        android:text="Android Sign in With Google"
        android:id="@+id/textView5"
        android:textSize="16sp"
        android:gravity="center"
        android:layout_below="@+id/textView3"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />

    <ImageView
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:id="@+id/imageView2"
        android:src="@drawable/google_icon"
        android:layout_marginTop="51dp"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true" />

</RelativeLayout>

Output of the above xml code will look like this.

android dashboard activity google sign in

 Writing Functionality of Dashboard Activity

At this time we need to implement functionality of DashboardActivity, open DashboardActivity.java and paste the following code.

public class DashboardActivity extends AppCompatActivity implements GoogleApiClient.OnConnectionFailedListener {

    private GoogleApiClient mGoogleApiClient;

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


    GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                .requestEmail()
                .build();

        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .enableAutoManage(this,this)
                .addApi(Auth.GOOGLE_SIGN_IN_API, gso)
                .build();

        Button _signout = (Button) findViewById(R.id.signout);
        Button _revoke = (Button) findViewById(R.id.revoke);

        String name = getIntent().getStringExtra("name");
        String email = getIntent().getStringExtra("email");
        String imagePath = getIntent().getStringExtra("pic");
        
        TextView _name = (TextView) findViewById(R.id.account_title);
        _name.setText(name);
        TextView _email = (TextView) findViewById(R.id.account_email);
        _email.setText(email.toUpperCase());
        ImageView _pic = (ImageView) findViewById(R.id.account_image);
        Picasso.with(this).load(imagePath).into(_pic);

        _signout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                Auth.GoogleSignInApi.signOut(mGoogleApiClient).setResultCallback(new ResultCallback<Status>() {
                    @Override
                    public void onResult(Status status) {

                        if(status.isSuccess()) {

                            Intent intent = new Intent(DashboardActivity.this,MainActivity.class);
                            startActivity(intent);
                            finish();

                        }
                        else {
                            Toast.makeText(DashboardActivity.this, status.getStatusMessage(), Toast.LENGTH_SHORT).show();
                        }
                        
                    }
                });
            }
        });

        _revoke.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Auth.GoogleSignInApi.revokeAccess(mGoogleApiClient).setResultCallback(new ResultCallback<Status>() {
                    @Override
                    public void onResult(Status status) {

                        if(status.isSuccess()) {

                            Intent intent = new Intent(DashboardActivity.this,MainActivity.class);
                            startActivity(intent);
                            finish();

                        }
                        else {
                            Toast.makeText(DashboardActivity.this, status.getStatusMessage(), Toast.LENGTH_SHORT).show();
                        }
                    }
                });
            }
        });

    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {

        Toast.makeText(DashboardActivity.this, connectionResult.getErrorMessage(), Toast.LENGTH_SHORT).show();

    }
}

 

Run the app and you will see the output like this.

 

android sign in with google dashboard

 

Congratulation! You have implemented Google Sign In in your Android Project. The Second part of this, is Login With Facebook.

if you find any error or logical error, please let me know 🙂

 

 

About the author

Yasir Ameen

I'm a programmer, teacher, and speaker. I work out of my home in Pakistan, Karachi for the Mobile, especially Android Platform. I discuss about technology, gadgets, codes, the devices we’re going and we’ve been. I’m excited about community, social equity, and media.

2 Comments

Leave a Comment