Google Sign in Android Example using Firebase Auth

Google Sign in Android Example using Firebase Auth. In this blog you’ll learn how to allow your Android app users to sign in to your app using Firebase Auth Tool and also access their data from Firebase Dashboard.

Need some career advice or prepping for an Android developer interview? Hit me up on Topmate.io, and let's chat!

Prerequisite

Creating Project at Firebase

To start, Sign in / Sign Up to Firebase.com using your Google Account. Once Signed in, click on ‘Add Project’.

Google Sign in Android Example

Create a new project and continue to dashboard.

Google Sign in Android Example

Once inside the dashboard, add an Android App to project and provide your app package name. (You can find this in your Android Studio project, ‘AndroidManifest.xml’ file.)

Google Sign in Android Example

Download ‘google-serivces.json’ file and add this to your Project as directed by Firebase.

Google Sign in Android Example

Inside Firebase Console

Go to Firebase Console, Select your Project and inside it go ‘Authentication’ from the left panel inside ‘Develop’ section.

Click on ‘Set up Sign-in method’.

Google Sign in Android Example

See for ‘Google’ in Provider section. Select that option and ‘Enable’ it. (Don’t forget to provide Email Address)

Google Sign in Android Example

Now switch back to your Android Studio Project!

Inside Android Studio

In Android Studio project make sure, you’ve added ‘google-services.json’ file.

Implement following libraries in your project by adding these line of codes to your build.gradle (Modeule: app)

    implementation 'com.google.firebase:firebase-core:16.0.6'
    implementation 'com.google.firebase:firebase-auth:16.1.0'
    implementation 'com.google.android.gms:play-services-auth:16.0.1'

Next, open ‘activity_main.xml’ file (or xml file where you want to put Google sign in button)

Add following lines of code to add Google Sign in Button:

   <com.google.android.gms.common.SignInButton
        android:id="@+id/signInButton"
        android:layout_width="250dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginBottom="48dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.496"
        app:layout_constraintStart_toStartOf="parent" />
Google Sign in Android Example

To learn how use gradient background in app as shown in preview, click to read here!

Now go to ‘MainActivity.java’ file and create SignInButton and few other objects as shown below.

SignInButton signInButton;
GoogleSignInClient mGoogleSignInClient;
final int RC_SIGN_IN = 123;
String TAG = "SignUp_Activity";
private FirebaseAuth mAuth;

in onCreate(); add this code:

signInButton = findViewById(R.id.signInButton);

Now we’ll need GoogleSignInOption object for requesting user details! Write following lines of code in onCreate();

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

        mGoogleSignInClient = GoogleSignIn.getClient(this, gso);

Now create a signIn(); method for app to show popup, so user can select his account and approve app request to his/her account details. Code is here:

    private void signIn() {
        Intent signInIntent = mGoogleSignInClient.getSignInIntent();
        startActivityForResult(signInIntent, RC_SIGN_IN);
    }

Set an on click listener for ‘SignInButton’ using following code in onCreate(); and call this signIn(); method

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

In the code above, once user clicks on button, the signIn(); method is called. Inside this method, intent is created and a result data is received.

To parse this code we will create a method called firebaseAuthWithGoogle(); which will take Google Sign in Account object as parameter.

    private void firebaseAuthWithGoogle(GoogleSignInAccount acct) {
        Log.d(TAG, "firebaseAuthWithGoogle:" + acct.getId());

        AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null);
        mAuth.signInWithCredential(credential)
                .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {
                        if (task.isSuccessful()) {
                            // Sign in success, update UI with the signed-in user's information
                            Log.d(TAG, "signInWithCredential:success");
                            FirebaseUser user = mAuth.getCurrentUser();
                             Intent intent = new Intent(MainActivity.this,HomeActivity.class);
        startActivity(intent);
                        } else {
                            // If sign in fails, display a message to the user.
                            Log.w(TAG, "signInWithCredential:failure", task.getException());
                            Toast.makeText(SignUp_Activity.this, "Authentication Failed.", Toast.LENGTH_SHORT).show();
                        }

                        // ...
                    }
                });
    }

In the code above, once the sign in succeeded, the user is directed to another activity called, ‘HomeActivity.class’. (Update UI as per your preference.)

Now, we’ll create another method named onActivityResult(); which will handle result received from Intent.

This method will have 3 parameters as shown below:


    @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) {
            Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
            try {
                // Google Sign In was successful, authenticate with Firebase
                GoogleSignInAccount account = task.getResult(ApiException.class);
                firebaseAuthWithGoogle(account);
            } catch (ApiException e) {
                // Google Sign In failed, update UI appropriately
                Log.w(TAG, "Google sign in failed", e);
                // ...
            }
        }
    }

Hurray!, we’re now finished implementing Google sign in button for Android. You can go ahead and test your app now.

Here is a full code for you to review what we did in MainActivity.class:

public class MainActivity extends AppCompatActivity {

    SignInButton signInButton;
    Button signUpBtn;
    GoogleSignInClient mGoogleSignInClient;
    final int RC_SIGN_IN = 123;
    String TAG = "SignUp_Activity";
    private FirebaseAuth mAuth;

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

        signInButton = findViewById(R.id.signInButton);

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

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

        mGoogleSignInClient = GoogleSignIn.getClient(this, gso);

    }

    private void signIn() {
        Intent signInIntent = mGoogleSignInClient.getSignInIntent();
        startActivityForResult(signInIntent, RC_SIGN_IN);
    }

    @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) {
            Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
            try {
                // Google Sign In was successful, authenticate with Firebase
                GoogleSignInAccount account = task.getResult(ApiException.class);
                firebaseAuthWithGoogle(account);
            } catch (ApiException e) {
                // Google Sign In failed, update UI appropriately
                Log.w(TAG, "Google sign in failed", e);
                // ...
            }
        }
    }

    private void firebaseAuthWithGoogle(GoogleSignInAccount acct) {
        Log.d(TAG, "firebaseAuthWithGoogle:" + acct.getId());

        AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null);
        mAuth.signInWithCredential(credential)
                .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {
                        if (task.isSuccessful()) {
                            // Sign in success, update UI with the signed-in user's information
                            Log.d(TAG, "signInWithCredential:success");
                            Intent intent = new Intent(SignUp_Activity.this,HomeActivity.class);
                            startActivity(intent);
                        } else {
                            // If sign in fails, display a message to the user.
                            Log.w(TAG, "signInWithCredential:failure", task.getException());
                            Toast.makeText(SignUp_Activity.this, "Authentication Failed.", Toast.LENGTH_SHORT).show();
                        }

                        // ...
                    }
                });
    }
    
}

View Comments (0)