How to use Firebase UI Authentication Library in Android?
Firebase UI is a library provided by Firebase for Android apps which makes or so many tasks easy while integrating Firebase in Android. This library provides so many extra features that we can integrate into our Android very easily. In this article, we will take a look at using this library for adding authentication in our Android apps.
What are The Benefits of Using Firebase UI Authentication Library?
- By using this library the code which we require for integrating any specific authentication reduces and it will become easier for user authentication flow.
- Using this library we can use multiple authentication providers at a time inside our apps such as email and password, Facebook, phone, Google, and many more.
- Account management tasks become easy while using this library.
- The login UI for each authentication provider is created by this library itself you can customize the UI according to the requirement.
- Using this library you will be able to safely link user accounts for different identities.
- With this library, you can add automatic integration with Smart Lock for passwords for cross-device sign in.
What We are Going to Build using Firebase UI Authentication Library?
Using this library we are simply creating an application in which we will be asking users to sign in using different login options such as Google, Email and password, and Phone number. After successful authentication of our user. We will redirect our user to a new screen where we will be displaying a simple welcome message to our user. Inside that screen, we will be adding a simple button that will be used to Log out the user from the application and redirects that user to the login screen for authentication. Below is the GIF in which you will get to know what we are going to build in this application. Note that we are going to implement this project using the Java language.
1) Phone Authentication
2) Email authentication
3) Google Authentication
Step by Step Implementation
Step 1: Create a new Android Studio Project
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.
Step 2: Connect your app to Firebase
After creating a new project in Android Studio. Connect your app to Firebase. For connecting your app to firebase. Navigate to Tools on the top bar. After that click on Firebase. A new window will open on the right side. Inside that window click on Authentication and then email and password authentication.
After clicking on email and password authentication you will get to see the below screen. Inside this screen click on the first option connect to firebase and after that click on the second option to add Firebase authentication to your app.
Step 3: Add the below dependency to build.gradle file
implementation ‘com.firebaseui:firebase-ui-auth:4.0.0’
Your Gradle files should be having the below dependencies present in the dependencies section.
Step 4: Add Internet permissions in the AndroidManifest.xml file
Navigate to the app > AndroidManifest.xml file inside that file add permission for the Internet. Add below lines in the AndroidManifest.xml file.
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Step 5: Working with the activity_main.xml file
You don’t have to add any type of view inside your activity_main.xml because we will be getting our UI from Firebase UI dependency itself we will be only customizing that UI according to our requirement. Navigate to the app > res > layout > activity_main.xml and add the below code to it.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
</RelativeLayout>
Step 6: Creating a new Activity for our Home Screen
Navigate to the app > java > your app’s package name > Right-click on it and then click on New > Empty Activity and give a name to your activity. Here we have given the name as HomeActivity.
Step 7: Creating a custom style for our Login Screen UI
We will be using a custom style for UI so we have created a custom style for our UI. For adding styles to your Login UI. Navigate to app > res > values > themes.xml and add the below code to it inside the <resources> tag.
<!--below is the custom theme which we will be using for our Login Screen-->
<!--We are using no action bar theme for our Login screen-->
<style name="Theme" parent="Theme.AppCompat.Light.NoActionBar">
<!--below line is for setting our text color to black-->
<item name="android:textColor">@color/black</item>
<!--we are setting our primary color to green-->
<item name="colorPrimary">@color/purple_500</item>
<!--we are setting our primary color dark to green-->
<item name="colorPrimaryDark">@color/purple_500</item>
<!--we are setting our edittext color to black-->
<item name="android:editTextColor">@color/black</item>
<!--we are setting our window background color to white-->
<item name="android:windowBackground">@color/white</item>
</style>
Step 8: Working with the MainActivity.java file
Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail.
import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import com.firebase.ui.auth.AuthUI;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import java.util.Arrays;
import java.util.List;
public class MainActivity extends AppCompatActivity {
// variable for Firebase Auth
private FirebaseAuth mFirebaseAuth;
// declaring a const int value which we
// will be using in Firebase auth.
public static final int RC_SIGN_IN = 1;
// creating an auth listener for our Firebase auth
private FirebaseAuth.AuthStateListener mAuthStateListener;
// below is the list which we have created in which
// we can add the authentication which we have to
// display inside our app.
List<AuthUI.IdpConfig> providers = Arrays.asList(
// below is the line for adding
// email and password authentication.
new AuthUI.IdpConfig.EmailBuilder().build(),
// below line is used for adding google
// authentication builder in our app.
new AuthUI.IdpConfig.GoogleBuilder().build(),
// below line is used for adding phone
// authentication builder in our app.
new AuthUI.IdpConfig.PhoneBuilder().build());
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// below line is for getting instance
// for our firebase auth
mFirebaseAuth = FirebaseAuth.getInstance();
// below line is used for calling auth listener
// for our Firebase authentication.
mAuthStateListener = new FirebaseAuth.AuthStateListener() {
@SuppressLint("ResourceType")
@Override
public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
// we are calling method for on authentication state changed.
// below line is used for getting current user which is
// authenticated previously.
FirebaseUser user = firebaseAuth.getCurrentUser();
// checking if the user
// is null or not.
if (user != null) {
// if the user is already authenticated then we will
// redirect our user to next screen which is our home screen.
// we are redirecting to new screen via an intent.
Intent i = new Intent(MainActivity.this, HomeActivity.class);
startActivity(i);
// we are calling finish method to kill or
// mainactivity which is displaying our login ui.
finish();
} else {
// this method is called when our
// user is not authenticated previously.
startActivityForResult(
// below line is used for getting
// our authentication instance.
AuthUI.getInstance()
// below line is used to
// create our sign in intent
.createSignInIntentBuilder()
// below line is used for adding smart
// lock for our authentication.
// smart lock is used to check if the user
// is authentication through different devices.
// currently we are disabling it.
.setIsSmartLockEnabled(false)
// we are adding different login providers which
// we have mentioned above in our list.
// we can add more providers according to our
// requirement which are available in firebase.
.setAvailableProviders(providers)
// below line is for customizing our theme for
// login screen and set logo method is used for
// adding logo for our login page.
.setLogo(R.drawable.gfgimage).setTheme(R.style.Theme)
// after setting our theme and logo
// we are calling a build() method
// to build our login screen.
.build(),
// and lastly we are passing our const
// integer which is declared above.
RC_SIGN_IN
);
}
}
};
}
@Override
protected void onResume() {
super.onResume();
// we are calling our auth
// listener method on app resume.
mFirebaseAuth.addAuthStateListener(mAuthStateListener);
}
@Override
protected void onPause() {
super.onPause();
// here we are calling remove auth
// listener method on stop.
mFirebaseAuth.removeAuthStateListener(mAuthStateListener);
}
}
Step 9: Working with the activity_home.xml file
Go to the activity_home.xml file and refer to the following code. Below is the code for the activity_home.xml file.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".HomeActivity">
<!--welcome message in text view-->
<TextView
android:id="@+id/idheadTV"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:padding="10dp"
android:text="Beginner for Beginner \n Welcome to Home Screen"
android:textAlignment="center"
android:textColor="@color/purple_500"
android:textSize="20sp" />
<!--Button for logout from the app-->
<Button
android:id="@+id/idBtnLogout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/idheadTV"
android:layout_centerHorizontal="true"
android:layout_marginTop="30dp"
android:text="Logout"
android:textAllCaps="false" />
</RelativeLayout>
Step 10: Working with the HomeActivity.java file
Go to the HomeActivity.java file and refer to the following code. Below is the code for the HomeActivity.java file. Comments are added inside the code to understand the code in more detail.
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import com.firebase.ui.auth.AuthUI;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
public class HomeActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
// button for logout and initializing our button.
Button logoutBtn = findViewById(R.id.idBtnLogout);
// adding onclick listener for our logout button.
logoutBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// below line is for getting instance
// for AuthUi and after that calling a
// sign out method from FIrebase.
AuthUI.getInstance()
.signOut(HomeActivity.this)
// after sign out is executed we are redirecting
// our user to MainActivity where our login flow is being displayed.
.addOnCompleteListener(new OnCompleteListener<Void>() {
public void onComplete(@NonNull Task<Void> task) {
// below method is used after logout from device.
Toast.makeText(HomeActivity.this, "User Signed Out", Toast.LENGTH_SHORT).show();
// below line is to go to MainActivity via an intent.
Intent i = new Intent(HomeActivity.this, MainActivity.class);
startActivity(i);
}
});
}
});
}
}
Step 11: Enable authentication providers in Firebase Console
For enabling Phone authentication in the Firebase console. Go to the Firebase Console. Now click on Go to Console option and navigate to your project. After that click on your project. You can get to see the below screen.
After clicking on Authentication you will get to see the below screen. On this screen click on the Sign-in method tab.
After clicking on the Sign in-method you will get to see below the list of authentication screens. Click on the Email and password option and enable it.
Click on the Email password option and you will get to see the below pop-up screen. Inside this screen click on the enable option and save it.
Now similarly click on the Phone option as shown below
Now you will get to see the below option after clicking on phone authentication enable phone authentication and save it.
Now we will enable Google Authentication by enabling it simply click on the Google option from the list.
After clicking on the Google option you will get to see the below pop-up message click on enable it and save it.
After enabling all authentication methods you will get to see the below screen with authentication.
After enabling this option in Firebase Console. Now run your app and test all the authentication. You can get to see the output in the below screen.
Output:
We have created three videos for output in which we have shown each authentication.
1) The First one is for Google Sig In Option
2) The Second one is for authentication using a phone number
3) The Third one is using Email and password authentication
GitHub Link: https://github.com/ChaitanyaMunje/FirebasePhoneAuthentication/tree/FirebaseUIAuthentication
Contact Us