DEV Community

Cover image for Google Sign-In on Android using Firebase
Offline Programmer
Offline Programmer

Posted on

Google Sign-In on Android using Firebase

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

Firebase Configuration

  • 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

  • Update the module (app-level) Gradle file by adding the Firebase Authentication Android library. You also need to add the Google Play services library.
    implementation 'com.google.firebase:firebase-auth'
    implementation 'com.google.android.gms:play-services-auth:19.0.0'
Enter fullscreen mode Exit fullscreen mode
  • Make sure to run Gradle Sync

LoginActivity

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

  • Update the AndroidManifest.xml file to set the LoginActivity as a Launcher.
...
        <activity android:name=".LoginActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
...
Enter fullscreen mode Exit fullscreen mode
  • Update activity_login.xml as below to add the SignIn button and a Progress bar
<?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>
Enter fullscreen mode Exit fullscreen mode
  • Declare the following variables on LoginActivity.java

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

Enter fullscreen mode Exit fullscreen mode
  • Update the onCreate method to set the setOnClickListener for signInButton and to call the configureGoogleClient() method

    @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();
    }

Enter fullscreen mode Exit fullscreen mode
  • The configureGoogleClient() is where you need to set Google Sign In Options and the FirebaseAuth. see below

    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();
    }

Enter fullscreen mode Exit fullscreen mode
  • The signInToGoogle() is where we will start the signIn intent as below.

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

Enter fullscreen mode Exit fullscreen mode
  • We will capture the result of launching the signIn Intent in the onActivityResult as below.

    @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);
            }
        }
    }

Enter fullscreen mode Exit fullscreen mode
  • We will use firebaseAuthWithGoogle to authenticate the user and launch the MainActivity.

    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);
                    }
                });
    }

Enter fullscreen mode Exit fullscreen mode
  • Update the onStart() method to check if the user is already signed in.

    @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();
        }
    }

Enter fullscreen mode Exit fullscreen mode

MainActivity

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

    <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" />

Enter fullscreen mode Exit fullscreen mode
  • Update the button onClick event to signOut the user and go back to the LoginActivity.

    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));
        }
    });

Enter fullscreen mode Exit fullscreen mode

Run the App

Check the code here

Follow me on Twitter for more tips about #coding, #learning, #technology, #Java, #JavaScript, #Autism, #Parenting...etc.

Check my Apps on Google Play

Cover image Brett Jordan

Top comments (0)