Saturday, 13 February 2016

Google plus Integration in Android |Sign in with Google plus in Android studio

Hello warriors how are you guys hope all of you doing excellent in programming finally after a long time I am back with a very cool and necessary topic in android Sign in with Google plus in android.



This is a necessary component of any app having Login functionality. There is a lot of tutorial over internet about this topic but trust me this post is going to be best and shortest tutorial for Google plus Integration in android.So Now time to implement this tutorial Let's start with coding like every post I will make module of steps for complete tutorial and then we will follow all the steps.


  • Create new Project in your Android studio.
  • Create new project on Google Developer console and enable Google sign In Api. 
  • Download googel-services.json file and configure it in your project.
  • Add Playservices dependency in build.gradle.
  • Add Internet Permission in manifest file.
  • Add Google SignIn Button in your activity_main.xml file  also add a Textview and a logout button.
  • Register both button and TextView in MainActivity.java.
  • Build GoogleSignInOptions in MainActivity and also add GoogleApiClient in MainActivity.
  • Call GoogleSignIn Api on click of SignIn button and update ui in onActivityResult method.
  • Add SignOut button functionality.


1.Create new project in your Android studio. Go to File>>New>>New project and select an empty Activity from Template and leave every thing as default.



2.Create new project on Google Developer console and enable Google sign In Api. This is very simple step just click on Google Developer console  and click on Get a Configuration File after clicking on this a new page will open like below image.


Fill App name and package name here and click on continue after this on new page add your system SHA1 key and Enable Google SignIn like below image.


After this scroll page to bottom and clcik on continue and on next page download googel-services.json like below image.



and finally our first and lengthy step is completed.

3.This step is very easy and short in this step we will copy downloaded googel-services.json file from your download folder and paste inside your app directory of project.

Go to YourProject>>app>> and paste your downloaded file here like below image.

4.This is very simple step open build.gradle file of project module and add playservices dependency file under dependencies like below image.



5.Add Internet permission to manifest :- In this step we need to add INTERNET permission to manifest file of our project add below line of code inside manifest .

<uses-permission android:name="android.permission.INTERNET" />
 6.Add Google SignIn Button in your activity_main.xml file  also add a Textview and a logout button.
 here is my activity_main.xml file you can copy and paste from here.

 7.Register both button and TextView in MainActivity.java. open your MainActivity.java file and Register both button and Textview like below code. I am also adding click listener to both button to manage click.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {


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

        tv_username= (TextView) findViewById(R.id.tv_username);
        
        //Register both button and add click listener 
        findViewById(R.id.sign_in_button).setOnClickListener(this);
        findViewById(R.id.btn_logout).setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {

    }
}

8.Build GoogleSignInOptions in MainActivity and also add GoogleApiClient in MainActivity. In this step i am doing two thing first build GoogleSignInOptions and second adding GoogleApiClient. make a instance of GoogleApiClient and add below code it will ask you to implement

GoogleApiClient.OnConnectionFailedListener

implement this Interface. here is code for GoogleSignInOption and GoogleApiClient.dont  forget to add an instance of GoogleApiClient above onCreate(). like this GoogleApiClient mGoogleApiClient.



1
2
3
4
5
6
7
8
 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();

9.Now lets implement on click of SignIn and SignOut button inside on click method. i am using two different method one for signIn and one for SignOut. and call these method from onClick. like below code.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
 @Override
    public void onClick(View v) {
        
        switch (v.getId()){
            case R.id.sign_in_button:
                
                signIn();
                
                break;
            case R.id.btn_logout:
                
                signOut();
                
                break;
        }

    }

and here is both signIn() and signOut() method.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
private void signIn() {
        Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
        startActivityForResult(signInIntent, RC_SIGN_IN);
    }

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

                    }
                });
    }

Inside signIn() you can see a varriable RC_SIGN_IN this is an integer varriable for request code of startActivityForResult method. you can use any value in my case this is 9001 like below.

                   private static final int RC_SIGN_IN = 9001;

Now override onActivityResult to get response form google SignIn activity. like below code.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
@Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

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

Here you can see method handleSignInResult(result), in this method parameter is result came from googleSignInActivity we will use this result to get data about user in this post i am setting name of user to Textview like below code.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
 private void handleSignInResult(GoogleSignInResult result) {

        if (result.isSuccess()) {
            // Signed in successfully, show authenticated UI.
            GoogleSignInAccount acct = result.getSignInAccount();
            tv_username.setText(getString(R.string.signed_in_fmt, acct.getDisplayName()));

        } else {
            // Signed out, show unauthenticated UI.
            // updateUI(false);
        }
    }

one last thing is to add a string in your resource>>value>>string.xml file

         <string name="signed_in_fmt">Signed in as: %s</string>

Now everything is set except one thing update ui in signOut method and setText to blank and you are done.

Here is my complete MainActivity.java file.

Still facing any problem comment below.

2 comments:

  1. My handleaigninresult always returns a false and the all crashes

    ReplyDelete
  2. My handleaigninresult always returns a false and the all crashes

    ReplyDelete