Google Sign-In on Android using Firebase
Tags: android, java, codenewbie, beginners
Published: 2020-11-19 22:25:12



Today I am going to show you how to use Firebase to integrate Google Sign-In into your app.. We will add this feature to the Android Application we created on the first post of the series

{% link https://dev.to/offlineprogrammer/firebase-analytics-for-android-shouldn-t-be-this-hard-4bn2 %} 

<p align="center">

<img align="center"  src="https://i.imgur.com/BYZ0681.jpg">

</p>

<h3>Firebase Configuration</h3>

- On the Firebase console, open the Authentication section, Click on Set up sign-in method .

![Screen Shot 2020-11-18 at 1.44.19 PM](https://i.imgur.com/UoivrGi.png)

- Update the module (app-level) Gradle file by adding the Firebase Authentication Android library. You also need to add the Google Play services library.

```shell
    implementation 'com.google.firebase:firebase-auth'
    implementation 'com.google.android.gms:play-services-auth:19.0.0'
```

- Make sure to run Gradle Sync

<h3>LoginActivity</h3>

- Add a new Empty Activity to the App and name it LoginActivity.

<p align="center">

<img align="center"  src="https://i.imgur.com/i5b6xVq.png">

</p>


- Update the AndroidManifest.xml file to set the LoginActivity as a Launcher.

```xml
...
        <activity android:name=".LoginActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
...
```

- Update activity_login.xml as below to add the SignIn button and a Progress bar

```xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".LoginActivity">
    
    <com.google.android.gms.common.SignInButton
        android:id="@+id/sign_in_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginBottom="8dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"  />

    <FrameLayout
        android:id="@+id/loginProgressLayout"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@android:color/transparent"
        android:gravity="center"
        android:orientation="vertical"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/sign_in_button">

        <ProgressBar
            android:id="@+id/log_in_progress"
            style="@android:style/Widget.DeviceDefault.Light.ProgressBar.Large.Inverse"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:background="@android:color/transparent"
            android:visibility="gone" />
    </FrameLayout>

</androidx.constraintlayout.widget.ConstraintLayout>
```

- Declare the following variables on LoginActivity.java

```java

GoogleSignInClient googleSignInClient;
ProgressBar mLogInProgress;
SignInButton signInButton;
FirebaseAnalytics mFirebaseAnalytics;

```

- Update the onCreate method to set the setOnClickListener for signInButton and to call the configureGoogleClient() method

```java

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        mLogInProgress = findViewById(R.id.log_in_progress);
        signInButton = findViewById(R.id.sign_in_button);
        signInButton.setSize(SignInButton.SIZE_WIDE);
        signInButton.setColorScheme(SignInButton.COLOR_LIGHT);
        signInButton.setOnClickListener(view -> {
            mLogInProgress.setVisibility(View.VISIBLE);
            signInToGoogle();
        });
        configureGoogleClient();
    }

```

- The configureGoogleClient() is where you need to set Google Sign In Options and the FirebaseAuth. see below

```java

    private void configureGoogleClient() {
        GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                // for the requestIdToken, this is in the values.xml file that
                // is generated from your google-services.json
                .requestIdToken(getString(R.string.default_web_client_id))
                .requestEmail()
                .build();
        // Build a GoogleSignInClient with the options specified by gso.
        googleSignInClient = GoogleSignIn.getClient(this, gso);
        // Set the dimensions of the sign-in button.
        SignInButton signInButton = findViewById(R.id.sign_in_button);
        signInButton.setSize(SignInButton.SIZE_WIDE);
        // Initialize Firebase Auth
        firebaseAuth = FirebaseAuth.getInstance();
    }

```

- The signInToGoogle() is where we will start the signIn intent as below.

```java

    public void signInToGoogle() {
        Intent signInIntent = googleSignInClient.getSignInIntent();
        startActivityForResult(signInIntent, RC_SIGN_IN);
    }

```

- We will capture the result of launching the signIn Intent in the onActivityResult as below.

```java

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable 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
                mLogInProgress.setVisibility(View.GONE);
            }
        }
    }

```

- We will use firebaseAuthWithGoogle to authenticate the user and launch the MainActivity.

```java

    private void firebaseAuthWithGoogle(GoogleSignInAccount account) {
        AuthCredential credential = GoogleAuthProvider.getCredential(account.getIdToken(), null);
        firebaseAuth.signInWithCredential(credential)
                .addOnCompleteListener(this, task -> {
                    if (task.isSuccessful()) {
                        // Sign in success, update UI with the signed-in user's information
                        FirebaseUser user = firebaseAuth.getCurrentUser();
                        if (user != null) {
                            startActivity(new Intent(LoginActivity.this, MainActivity.class));
                            finish();
                        }
                    } else {
                        // failed
                        mLogInProgress.setVisibility(View.GONE);
                    }
                });
    }

```

- Update the onStart() method to check if the user is already signed in.

```java

    @Override
    public void onStart() {
        super.onStart();
        // Check if user is signed in (non-null) and update UI accordingly.
        FirebaseUser currentUser = firebaseAuth.getCurrentUser();
        if (currentUser != null) {
            mLogInProgress.setVisibility(View.VISIBLE);
            signInButton.setVisibility(View.GONE);
            startActivity(new Intent(LoginActivity.this, MainActivity.class));
            finish();
        }
    }

```


<h3>MainActivity</h3>

- Let's use the button for signing out. Update the text of the Button on activity_main.xml as below.

```xml

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Sign Out"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.528"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.648" />

```

- Update the button onClick event to signOut the user and go back to the LoginActivity.

```java

    Button button = findViewById(R.id.button);
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            mFirebaseAnalytics.logEvent("button_clicked", null);
            FirebaseAuth.getInstance().signOut();
            startActivity(new Intent(MainActivity.this, LoginActivity.class));
        }
    });

```

<h3>Run the App</h3>

<p align="center">

<img align="center"  src="https://i.imgur.com/lQXrjKb.gif">

</p>


<p align="center">

<img align="center"  src="https://i.imgur.com/lRVwYxo.jpg">

</p>





Check the code <a href="https://github.com/offlineprogrammer/AndroidAnalyticsTest">here</a>

> Follow me on <a href="https://twitter.com/MohammedMalaka">Twitter</a> for more tips about #coding, #learning, #technology, #Java, #JavaScript, #Autism, #Parenting...etc.

> Check my Apps on <a href="https://bit.ly/3h05gQ7">Google Play</a>

> <span>Cover image <a href="https://unsplash.com/@brett_jordan?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Brett Jordan</a></span>