Android Tutorial

Software Setup and Configuration

Android Studio

File Structure

Components

Core Topics

Layout

View

Button

Intent and Intent Filters

Toast

RecyclerView

Fragments

Adapters

Other UI Component

Image Loading Libraries

Date and Time

Material Design

Bars

Working with Google Maps

Chart

Animation

Database

Advance Android

Jetpack

Architecture

App Publish

App Monetization

User authentication using Firebase in Android

Firebase Authentication provides backend services to authenticate users to your app. It supports authentication using passwords, phone numbers, popular federated identity providers like Google, Facebook, and Twitter, and more.

Here's a step-by-step guide on how to implement user authentication using Firebase in an Android application:

1. Set up Firebase:

  • Create a Firebase project on the Firebase Console.
  • In the Firebase Console, navigate to your project, and click on Add App, then select the Android icon to add an Android app to your Firebase project.
  • Register your app by providing your app's package name.
  • Download the google-services.json file and place it in your app's app/ directory.

2. Add Firebase Authentication dependencies:

In your app-level build.gradle:

implementation 'com.google.firebase:firebase-auth:21.0.1'  // Check for the latest version
apply plugin: 'com.google.gms.google-services'

3. Initialize Firebase:

In your main Application or Activity class:

FirebaseApp.initializeApp(this)

4. Sign up & Sign in with Email and Password:

a. Sign Up:

val auth = FirebaseAuth.getInstance()

val email = "user@example.com"
val password = "password123"
auth.createUserWithEmailAndPassword(email, password)
    .addOnCompleteListener(this) { task ->
        if (task.isSuccessful) {
            val user = auth.currentUser
            // Handle user registration success
        } else {
            // Handle error
        }
    }

b. Sign In:

auth.signInWithEmailAndPassword(email, password)
    .addOnCompleteListener(this) { task ->
        if (task.isSuccessful) {
            val user = auth.currentUser
            // Handle user sign in success
        } else {
            // Handle error
        }
    }

5. Sign Out:

auth.signOut()

6. (Optional) Additional authentication methods:

Firebase Authentication supports various other methods of authentication:

  • Phone Number Authentication: Users can sign in using a phone number.
  • Google Sign-In: Authenticate users with their Google Accounts.
  • Facebook Login: Authenticate users with their Facebook accounts.
  • Twitter Login: Authenticate users with their Twitter accounts.

Each of these methods requires additional setup steps and configurations.

7. Listen to authentication state changes:

You can use FirebaseAuth.AuthStateListener to listen for changes in the user's authentication state:

val authListener = FirebaseAuth.AuthStateListener { firebaseAuth ->
    val user = firebaseAuth.currentUser
    if (user != null) {
        // User is signed in
    } else {
        // User is signed out
    }
}

// Attach the listener in onStart():
override fun onStart() {
    super.onStart()
    auth.addAuthStateListener(authListener)
}

// Remove the listener in onStop():
override fun onStop() {
    super.onStop()
    auth.removeAuthStateListener(authListener)
}

This is just a basic overview of user authentication with Firebase in Android. Depending on your requirements, you might need to dive deeper into Firebase's documentation to handle more advanced scenarios or other authentication methods.

  1. Firebase email/password authentication in Android example:

    • Description: Allows users to register and log in using their email and password.
    • Example Code:
      FirebaseAuth.getInstance().createUserWithEmailAndPassword(email, password)
          .addOnCompleteListener(this, task -> {
              if (task.isSuccessful()) {
                  FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
              } else {
                  // Handle registration failure
              }
          });
      
  2. Phone number authentication with Firebase in Android:

    • Description: Enables user authentication using their phone number.
    • Example Code:
      PhoneAuthOptions options =
          PhoneAuthOptions.newBuilder(FirebaseAuth.getInstance())
              .setPhoneNumber(phoneNumber)       // Phone number to verify
              .setTimeout(60L, TimeUnit.SECONDS) // Timeout duration
              .setActivity(this)                 // Activity (for callback binding)
              .setCallbacks(callbacks)           // OnVerificationStateChangedCallbacks
              .build();
      
      PhoneAuthProvider.verifyPhoneNumber(options);
      
  3. Firebase authentication and social logins in Android:

    • Description: Integrates authentication with social platforms like Google, Facebook, or Twitter.
    • Example Code:
      AuthCredential credential = GoogleAuthProvider.getCredential(idToken, null);
      
      FirebaseAuth.getInstance().signInWithCredential(credential)
          .addOnCompleteListener(this, task -> {
              if (task.isSuccessful()) {
                  FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
              } else {
                  // Handle social login failure
              }
          });
      
  4. Customizing Firebase authentication UI in Android:

    • Description: Customizes the UI for Firebase authentication, providing a seamless user experience.
    • Example Code:
      startActivityForResult(
          AuthUI.getInstance()
              .createSignInIntentBuilder()
              .setAvailableProviders(providers)
              .build(),
          RC_SIGN_IN);
      
  5. Firebase authentication callbacks and events in Android:

    • Description: Handles authentication callbacks and events to respond to different authentication states.
    • Example Code:
      FirebaseAuth.getInstance().addAuthStateListener(auth -> {
          FirebaseUser user = auth.getCurrentUser();
          if (user != null) {
              // User is signed in
          } else {
              // User is signed out
          }
      });
      
  6. Firebase authentication and authorization in Android:

    • Description: Combines Firebase authentication with Firebase Realtime Database or Firestore for secure access control.
    • Example Code:
      DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("restrictedData");
      
      databaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
          @Override
          public void onDataChange(DataSnapshot dataSnapshot) {
              // Access restricted data
          }
      
          @Override
          public void onCancelled(DatabaseError databaseError) {
              // Handle error
          }
      });
      
  7. Firebase anonymous authentication in Android example:

    • Description: Allows users to access certain features without requiring a full account.
    • Example Code:
      FirebaseAuth.getInstance().signInAnonymously()
          .addOnCompleteListener(this, task -> {
              if (task.isSuccessful()) {
                  FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
              } else {
                  // Handle anonymous login failure
              }
          });
      
  8. Firebase authentication and user profiles in Android:

    • Description: Manages user profiles associated with Firebase accounts.
    • Example Code:
      FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
      
      UserProfileChangeRequest profileUpdates = new UserProfileChangeRequest.Builder()
          .setDisplayName("John Doe")
          .setPhotoUri(Uri.parse("https://example.com/profile.jpg"))
          .build();
      
      user.updateProfile(profileUpdates)
          .addOnCompleteListener(task -> {
              if (task.isSuccessful()) {
                  // Profile updated
              }
          });