Intergrate google sign in android using firebase authentication

Posted By : Keshav Gupta | 22-Oct-2017

Configuration on server side:

1. Create a project on firebase console.Click on this link

   https://console.firebase.google.com/u/1/

2. Add project name and tap on CREATE PROJECT 

3. In next screen add firebase to your application by selecting option "Add Firebase to your Android app"

4. Next a popup screen will appear and enter package name and shai key for project.

5. Download google-services.json file and copy in project.

6.Do following changes in your project gradle file

 

Project-level build.gradle (<project>/build.gradle):

buildscript {
  dependencies {
    // Add this line
    classpath 'com.google.gms:google-services:3.1.0'
  }
}
App-level build.gradle (<project>/<app-module>/build.gradle):

...
// Add to the bottom of the file
apply plugin: 'com.google.gms.google-services'

7. Now you have successfully added firebase to your project.

8. Now open authentication section in project side bar and select sign in tab and enable google tab.

   *Now all server side configuration has been done successfully.

Integration in project code :

1.Add following line of code in app/build.gradle/dependencies.

 

    compile 'com.google.firebase:firebase-auth:9.4.0'
    compile 'com.google.android.gms:play-services-auth:9.4.0'

2.Create a helper class named as GoogleLoginController  and add following in class file.

 

    private static final String TAG = "GoogleActivity";
    private Context context;
    private  GoogleSignInOptions gso;
    public  static final int RC_SIGN_IN = 9001;
    private GoogleApiClient mGoogleApiClient;

3. Instantiate the class and assign gso and mGoogleApiClient.Code will be like this:

 

public GoogleLoginController(Context context)
 {
     this.context=context;
 }
public void initializeApiClient()
  {
       gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
               .requestIdToken(context.getResources().getString(R.string.gplusapplicationid))
               .requestEmail()
               .build();

             // use this when signin button activity extends FragmentActivity and use enable auto manage

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

              // else use this

        mGoogleApiClient=new GoogleApiClient.Builder(context).
                addApi(Auth.GOOGLE_SIGN_IN_API, gso)
                .addConnectionCallbacks(this)
               .addOnConnectionFailedListener(this)
               .build();
  }

3. Create methods for sign in and sign out and connection callback.Code will be like this:

 

public void makeGoogleLoggeedIn()
 {
     Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
     ((AppCompatActivity)context).startActivityForResult(signInIntent, RC_SIGN_IN);
 }

@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
    Logger.LogDebug(TAG, "onConnectionFailed:" + connectionResult);
    Toast.makeText(context, "Google Play Services error.", Toast.LENGTH_SHORT).show();
}
// [START signOut]
public void signOut() {
    if (mGoogleApiClient != null && mGoogleApiClient.isConnected()) {
        mGoogleApiClient.stopAutoManage((AppCompatActivity)context);
        mGoogleApiClient.disconnect();
    }
   }

@Override
public void onConnected(@Nullable Bundle bundle) {
    Toast.makeText(context, "Gplus connected", Toast.LENGTH_SHORT).show();
}

@Override
public void onConnectionSuspended(int i) {
    Toast.makeText(context, "Gplus connection suspended", Toast.LENGTH_SHORT).show();

4.Final code for helper class will be like this.

 

public class GoogleLoginController implements GoogleApiClient.OnConnectionFailedListener, GoogleApiClient.ConnectionCallbacks {
    private static final String TAG = "GoogleActivity";
    private Context context;
    private  GoogleSignInOptions gso;
    public  static final int RC_SIGN_IN = 9001;
    private GoogleApiClient mGoogleApiClient;
     public GoogleLoginController(Context context)
     {
         this.context=context;
     }
    public void initializeApiClient()
      {
           gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                   .requestIdToken(context.getResources().getString(R.string.gplusapplicationid))
                   .requestEmail()
                   .build();

                 // use this when signin button activity extends FragmentActivity and use enable auto manage

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

                  // else use this

            mGoogleApiClient=new GoogleApiClient.Builder(context).
                    addApi(Auth.GOOGLE_SIGN_IN_API, gso)
                    .addConnectionCallbacks(this)
                   .addOnConnectionFailedListener(this)
                   .build();
      }
     public void makeGoogleLoggeedIn()
     {
         Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
         ((AppCompatActivity)context).startActivityForResult(signInIntent, RC_SIGN_IN);
     }

    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
        Logger.LogDebug(TAG, "onConnectionFailed:" + connectionResult);
        Toast.makeText(context, "Google Play Services error.", Toast.LENGTH_SHORT).show();
    }
    // [START signOut]
    public void signOut() {
        if (mGoogleApiClient != null && mGoogleApiClient.isConnected()) {
            mGoogleApiClient.stopAutoManage((AppCompatActivity)context);
            mGoogleApiClient.disconnect();
        }
    }

    @Override
    public void onConnected(@Nullable Bundle bundle) {
        Toast.makeText(context, "Gplus connected", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onConnectionSuspended(int i) {
        Toast.makeText(context, "Gplus connection suspended", Toast.LENGTH_SHORT).show();
    }
}

5.Now to use this class in LoginActivity class 

On click of custom button of ui.Make these calls stated below.

 

 googleLoginController = new GoogleLoginController(activity);
                googleLoginController.signOut();
                googleLoginController.initializeApiClient();
                signInButton.performClick();
                googleLoginController.makeGoogleLoggeedIn();

6. Add connection callback and request for profile data in activity class

 

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

        // add line for gplus signin callback
    if (requestCode == GoogleLoginController.RC_SIGN_IN) {
        GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
        handleSignInResult(result);
    }
}

private void handleSignInResult(GoogleSignInResult result) {
    Log.d("GOOGLE", "handleSignInResult:" + result.isSuccess());
    if (result.isSuccess()) {
        // Signed in successfully, show authenticated UI.
        GoogleSignInAccount acct = result.getSignInAccount();
        Logger.LogError("RESULT", acct.getEmail());
        Logger.LogError("RESULT", acct.getIdToken());
        Logger.LogError("RESULT", acct.getId());
        Logger.LogError("RESULT", acct.getGivenName());
        Logger.LogError("RESULT", acct.getFamilyName());
        Logger.LogError("RESULT", acct.getDisplayName());
        Logger.LogError("RESULT", acct.getPhotoUrl().getPath());
    } else {
        Toast.makeText(activity,R.string.gplusloginfailed, Toast.LENGTH_LONG).show();
    }
}

This was all to do for integrating google sign in.

About Author

Author Image
Keshav Gupta

Keshav Gupta is Android Developer in Oodles, he always look forward for new tasks and new things to learn more.

Request for Proposal

Name is required

Comment is required

Sending message..