Login with Google Plus example

In this tutorial we will learn about how to integrate google plus login into Android Studio project with a simple example.

Things we need to do:

  1. Create Project inAndrod Studio
  2. Create Project in Google Developers Console
  3. Code the project in Android Studio

Create Project in Android Studio:

  • Create a new project in Android Studio 
  • Copy and paste the below dependency in build.gradle file for google play services
   compile 'com.google.android.gms:play-services:9.0.1'
  • Copy and paste the below dependency in build.gradle file for displaying image from url
   compile 'com.squareup.picasso:picasso:2.5.2'

Create Project in Google Developers Console:

1.
Create a project
2.
Enter project name
3.
Select G+ API
4.
Enable API
5.
Create credentials
6.
Fill up the credentials
  • In Android Studio right side of IDE click on Gradle and follow the Image 8. to get SHA1
7.
8.
Fill SHA and package
9.
Fill Email and project name
  • Copy and paste the downloaded file in your project's app directory in Android Studio
10.
11.
Click on credentials to restrict key
12.
Click on API key
13.
Click on Restrict key
14.
Fill all the info and save

Code project in Android Studio.

  • Now add the internet permission and meta data parameter in the manifest of your project. Your manifest should look like this
File: Manifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="infinite.hss.com.glogin">

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

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">

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

        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>
  • Copy and paste the following code in your activity_main.xml
File: activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:orientation="vertical"
    tools:context="infinite.hss.com.glogin.MainActivity">


    <ImageView
        android:id="@+id/img_profile"
        android:layout_width="120dp"
        android:layout_height="120dp"
        android:layout_margin="20dp"
        android:src="@drawable/user_pic" />

    <TextView
        android:id="@+id/txt_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:text="Name"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/txt_email"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:text="Email Id"
        android:textStyle="bold" />


    <Button
        android:id="@+id/btn_G"
        style="?android:attr/borderlessButtonStyle"
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:layout_margin="40dp"
        android:background="#FF0000"
        android:text="Log in with G+"
        android:textColor="#ffffff" />

    <Button
        android:id="@+id/btn_logOut"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="30dp"
        android:layout_marginRight="30dp"
        android:background="@color/colorPrimary"
        android:text="Logout"
        android:textColor="#ffffff"
        android:visibility="gone" />


</LinearLayout>


  • Copy and paste the following code in your MainActivity.java file
File: MainActivity.java:
package infinite.hss.com.glogin;

import android.content.Intent;
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.Auth;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.auth.api.signin.GoogleSignInResult;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.squareup.picasso.Picasso;

public class MainActivity extends AppCompatActivity implements GoogleApiClient.OnConnectionFailedListener {

    private GoogleSignInOptions gso;
    private GoogleApiClient mGoogleApiClient;
    private int RC_SIGN_IN = 100;
    Button btn_google, btn_logout;
    TextView txt_name, txt_email;
    ImageView img_profile;

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

        btn_google = (Button) findViewById(R.id.btn_G);
        txt_name = (TextView) findViewById(R.id.txt_name);
        txt_email = (TextView) findViewById(R.id.txt_email);
        img_profile = (ImageView) findViewById(R.id.img_profile);
        btn_logout = (Button) findViewById(R.id.btn_logOut);

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

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

        btn_google.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                signIn();
            }
        });

        btn_logout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Auth.GoogleSignInApi.signOut(mGoogleApiClient);
                btn_google.setVisibility(View.VISIBLE);
                btn_logout.setVisibility(View.GONE);
                txt_name.setText("Name");
                txt_email.setText("Email Id");
                img_profile.setImageResource(R.drawable.user_pic);
            }
        });
    }

    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

    }

    private void signIn() {
        //Creating an intent
        Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
        //Starting intent for result
        startActivityForResult(signInIntent, RC_SIGN_IN);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == RC_SIGN_IN) {
            GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
            //Calling a newc function to handle signin
            SignInResult(result);
        }

    }

    //After the signing we are calling this function
    private void SignInResult(GoogleSignInResult result) {
        //If the login succeed
        if (result.isSuccess()) {
            // Signed in successfully, show authenticated UI.
            GoogleSignInAccount acct = result.getSignInAccount();

            String personName = acct.getDisplayName();
            String imageUrl = acct.getPhotoUrl().toString();
            String email = acct.getEmail();

            Log.e("Google", "Name: " + personName + ", email: " + email
                    + ", Image: " + imageUrl);

            // set image url to imageview
            Picasso.with(MainActivity.this).load(imageUrl).into(img_profile);
            // setting values
            txt_name.setText(personName);
            txt_email.setText(email);
            btn_logout.setVisibility(View.VISIBLE);
            btn_google.setVisibility(View.GONE);

        } else {
            //If login fails
            Toast.makeText(this, "Login Failed", Toast.LENGTH_LONG).show();
        }
    }

}


  • Now run the project and enjoy the output
Output:
Thank you...

Comments