Skip to main content

Android Integrating Google Sign-In

Now-a-days, most users prefer to sign up with Google rather than filling a registration form. Google sign-in integration makes your app user-friendly.
Following are the steps to integrate google sign-in :
1. In android studio, open SDK Manager and install Google Repository.
2. Create new project in android studio and copy the package name (will be used in next step).
3. To integrate google sign-in, google-services.json is needed. Infact, whenever we use any Google api we need this file. Go to Android quick start and get a configuration file for your project.Enter the same package name as above.
4. Now, you have to provide SHA-1 fingerprint to use Google Sign-In. To generate SHA-1 , open command prompt and enter this command-
keytool -list -v -keystore "C:\Users\%UserName%\.android\debug.keystore" -alias androiddebugkey -storepass android -keypass android

If it asks for password then enter android. Now, Paste SHA-1 and click on Enable Google Sign-In and then click on Generate configuration files and download google-services.json file.
5. Copy the google-services.json file into the app/ folder of your android project.
6. Now, add following dependencies in app level and project level gradle files.
  • Open project-level build.gradle and add dependency.
dependencies {       
        classpath 'com.google.gms:google-services:3.0.0'      
    }
  • Open app-level build.gradle and add plugin and dependency.
dependencies {
    compile 'com.google.android.gms:play-services-auth:10.2.0'    }
apply plugin: 'com.google.gms.google-services'
7. Open activity_main.xml and add the following code-

<?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:orientation="vertical"
    android:padding="10dp"
    tools:context="com.gunjan.andriodcodesnippets.MainActivity">
   <TextView
       android:id="@+id/tv_signin"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:text="Google Sign-In"
       android:textSize="30sp"
       />
   <com.google.android.gms.common.SignInButton
       android:layout_height="wrap_content"
       android:layout_width="wrap_content"
       android:id="@+id/googleLoginButton"
       android:layout_marginTop="30dp">
   </com.google.android.gms.common.SignInButton>
   <Button
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:text="Sign Out"
       android:id="@+id/bt_sign_out"
       android:layout_marginTop="30dp"
       android:visibility="gone"/>
</LinearLayout>
8. Now, in MainActivity.java , we need to add following-
  • In onCreate() Method, create object of GoogleSignInOptions and GoogleApiClient.
  • Implement interface GoogleApiClient.OnConnectionFailedListener and its method.
  • Implement signIn() and onActivityResult() methods.
  • Add handleSignInResult() and get emailId.
  • Add updateUI() method to update the interface.
  • Implement onStart() method to check if the user has already signed in.
  • Implement signOut() method.
public class MainActivity extends AppCompatActivity
        implements GoogleApiClient.OnConnectionFailedListener,View.OnClickListener{

    GoogleApiClient mGoogleApiClient;
    private int RC_SIGN_IN=9001;
    TextView tv_signin;
    String emailID;
    Button bt_signOut;
    SignInButton googleLoginButton;

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

        tv_signin=(TextView)findViewById(R.id.tv_signin);
        bt_signOut=(Button)findViewById(R.id.bt_sign_out);
        googleLoginButton=(SignInButton)findViewById(R.id.googleLoginButton);

        bt_signOut.setOnClickListener(this);
        googleLoginButton.setOnClickListener(this);

        //Google Sign-In
        GoogleSignInOptions gso=new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                .requestProfile()
                .requestEmail()
                .build();

        mGoogleApiClient=new GoogleApiClient.Builder(this)
                .enableAutoManage(this,this)
                .addOnConnectionFailedListener(this)
                .addApi(Auth.GOOGLE_SIGN_IN_API,gso)
                .build();
    }
    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
        Toast.makeText(this,"Couldn't sign in",Toast.LENGTH_LONG).show();
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.googleLoginButton:
                signIn();
                break;
            case R.id.bt_sign_out:
                signOut();
        }
    }
    private void signIn() {
        Intent signInIntent= Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
        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);
            handleSignInResult(result);
        }

    }
    private void handleSignInResult(GoogleSignInResult result){
        if(result.isSuccess()){
            GoogleSignInAccount account=result.getSignInAccount();
            emailID=account.getEmail();
            updateUI(true);
        }
        else {
            updateUI(false);
        }
    }
    private void updateUI(boolean SignInSuccessful) {
        if(SignInSuccessful){
            //If sign-in successful, show the emailID, hide the sign-in button and show sign out button.
            tv_signin.setText(emailID);
            findViewById(R.id.googleLoginButton).setVisibility(View.GONE);
            findViewById(R.id.bt_sign_out).setVisibility(View.VISIBLE);
        }else {
            //If sign-in unsuccessful or user click sign-out, hide the sign-out button and show sign in button.
            tv_signin.setText("Google Sign-In");
            findViewById(R.id.googleLoginButton).setVisibility(View.VISIBLE);
            findViewById(R.id.bt_sign_out).setVisibility(View.GONE);
        }
    }
    //Check if already signed In
    @Override
    protected void onStart() {
        super.onStart();
        OptionalPendingResult<GoogleSignInResult> opr=Auth.GoogleSignInApi.silentSignIn(mGoogleApiClient);
        if(opr.isDone()){
            GoogleSignInResult result=opr.get();
            Log.e("Test","signed in already");
            handleSignInResult(result);
        }
        else {
            Log.e("Test","Not signed in");
            opr.setResultCallback(new ResultCallback<GoogleSignInResult>() {
                @Override
                public void onResult(@NonNull GoogleSignInResult result) {
                    handleSignInResult(result);

                }
            });
        }
    }
    private void signOut() {
        Auth.GoogleSignInApi.signOut(mGoogleApiClient).setResultCallback(
                new ResultCallback<Status>() {
                    @Override
                    public void onResult(Status status) {
                        updateUI(false);
                    }
                });
    }
}
9. Run the project.


Comments

Popular Posts