Skip to content
Tutorials Center
My learning

Topics

Lesson 77 of 104 ยท Networking

Firebase on Android: Auth, Firestore, Realtime Database and FCM

Add Firebase to an Android app: BoM and google-services.json, email sign-in, Firestore versus Realtime Database, security rules, FCM push tokens and Crashlytics.

Many apps need the same backend pieces: sign-in, a database that syncs, push notifications, crash reports. Building them yourself means servers, security and a lot of waiting. Firebase is Google's backend-as-a-service for this. You add a few libraries, configure a project in the Firebase console, and your app talks to managed services directly, with no server of your own. It is a good way to get a prototype or a small product running, and it has real limits that are worth understanding before you commit.

This lesson covers setup, Authentication, the two databases (Cloud Firestore and the Realtime Database), the security rules that protect your data, Cloud Messaging (FCM) for push notifications, and the Crashlytics and Analytics tools. Firebase needs a real Google project and an emulator or device, so the real code here is read-only. The TryIts are plain Kotlin stand-ins that model a document store, a rules check, listeners and token handling, and the text says which part is real. Firebase is one choice, not the default: for a REST backend you run yourself, see Retrofit.

Setting up a project

Setup has three parts, and mistakes in any of them produce confusing errors.

  1. Create a Firebase project in the Firebase console and register your Android app with its package name (the applicationId). Add your signing certificate's SHA-1 and SHA-256 fingerprints for sign-in features that need them (see Signing and Release Builds); debug and release builds have different fingerprints.
  2. Download google-services.json and place it in the app/ module. It holds your project ID, API key and app ID. It is configuration, not a secret, but keep it out of public repositories if you can, and never confuse it with a server key.
  3. Apply the Google Services plugin and add libraries with the Firebase BoM (Bill of Materials), which pins compatible versions so you do not list one for each library.
Kotlin
// read-only example: app/build.gradle.kts (check the Firebase release notes for current versions)
plugins {
    id("com.android.application")
    id("com.google.gms.google-services")        // reads google-services.json
}

dependencies {
    implementation(platform("com.google.firebase:firebase-bom:<version>"))
    implementation("com.google.firebase:firebase-auth")
    implementation("com.google.firebase:firebase-firestore")
    implementation("com.google.firebase:firebase-messaging")
    implementation("com.google.firebase:firebase-crashlytics")
    implementation("com.google.firebase:firebase-analytics")
}

Because of the BoM, the individual Firebase libraries have no version. Firebase also initializes itself automatically at app start (a content provider reads the JSON), so you rarely call FirebaseApp.initializeApp() yourself. See Gradle for Android for how plugins and dependencies fit together.

Firebase has no "back end code" to hide an API key in: your app talks to the services directly, so security rules are your only access control. The configuration file being public is fine only because the rules decide who can do what.

Authentication

Firebase Authentication handles accounts so you do not store passwords. It supports email and password, phone numbers, anonymous users, and federated sign-in with Google and other providers (through Credential Manager on current Android). After sign-in, FirebaseAuth keeps the user and refreshes the ID token for you; the user stays signed in across restarts until they sign out.

Kotlin
// read-only example: email sign-up and sign-in with coroutines (kotlinx-coroutines-play-services)
class AuthRepository(private val auth: FirebaseAuth = Firebase.auth) {

    val currentUserId: String? get() = auth.currentUser?.uid

    // A Flow that emits whenever the user signs in or out
    val signedIn: Flow<Boolean> = callbackFlow {
        val listener = FirebaseAuth.AuthStateListener { trySend(it.currentUser != null) }
        auth.addAuthStateListener(listener)
        awaitClose { auth.removeAuthStateListener(listener) }
    }

    suspend fun signUp(email: String, password: String): Result<String> = runCatching {
        auth.createUserWithEmailAndPassword(email, password).await().user!!.uid
    }

    suspend fun signIn(email: String, password: String): Result<String> = runCatching {
        auth.signInWithEmailAndPassword(email, password).await().user!!.uid
    }

    fun signOut() = auth.signOut()
}

The pattern is familiar from the repository lesson: a class wraps the Firebase API, exposes suspend functions and a Flow, and the ViewModel never touches Firebase types directly. await() comes from the kotlinx-coroutines-play-services artifact, and it turns Google's Task into a suspending call. Failures such as a wrong password or an existing account arrive as exceptions (FirebaseAuthException subclasses), which is why runCatching appears here.

The first stand-in models the state machine behind it: sign-up, sign-in, an auth state listener, and the uid that rules will later use.

Kotlin Auth state and listeners (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Firestore or Realtime Database?

Firebase has two databases, and beginners often pick the wrong one. Both sync data to clients in real time and work offline (they cache locally and send changes when the connection returns). They differ in how data is shaped and priced.

Cloud Firestore Realtime Database
Data model Collections of documents (fields, subcollections) One big JSON tree
Queries Indexed, combine filters and sorting, paginate Limited: sort and filter on one key
Scaling Automatic, multi-region Scale by sharding across instances
Billing Per read, write, delete (plus storage) Bandwidth and storage
Offline Enabled by default on Android Must be switched on (setPersistenceEnabled)
Best for Most new apps, structured data Very frequent small updates, presence, live cursors

Choose Firestore for most apps: it models data you would otherwise keep in tables, supports richer queries and has clear rules. Choose the Realtime Database for high-frequency, low-latency state such as "who is online" or a live typing indicator. You can use both in one app.

Reading and writing Firestore

A Firestore document is a set of fields addressed by a path such as users/ada/notes/n1. Documents live in collections, and a document can own subcollections.

Kotlin
// read-only example: a repository over Firestore
data class Note(
    val id: String = "",
    val ownerId: String = "",
    val title: String = "",
    val done: Boolean = false,
)                                  // a no-argument constructor is needed for toObject()

class NotesRepository(private val db: FirebaseFirestore = Firebase.firestore) {

    private val notes = db.collection("notes")

    suspend fun add(ownerId: String, title: String): String =
        notes.add(mapOf("ownerId" to ownerId, "title" to title, "done" to false)).await().id

    suspend fun setDone(id: String, done: Boolean) {
        notes.document(id).update("done", done).await()       // changes one field
    }

    suspend fun delete(id: String) { notes.document(id).delete().await() }

    // A live query as a Flow: emits again on every change, from cache first
    fun observe(ownerId: String): Flow<List<Note>> = callbackFlow {
        val registration = notes
            .whereEqualTo("ownerId", ownerId)
            .orderBy("title")
            .addSnapshotListener { snapshot, error ->
                if (error != null) { close(error); return@addSnapshotListener }
                trySend(snapshot!!.documents.mapNotNull { doc ->
                    doc.toObject(Note::class.java)?.copy(id = doc.id)
                })
            }
        awaitClose { registration.remove() }          // stop listening when the Flow is cancelled
    }
}

Three habits matter. First, always remove listeners: awaitClose { registration.remove() } ties the listener to the Flow's collection, and in Compose you collect it with the lifecycle-aware tools from Collecting Flows Safely. Second, billing counts every document read, so a query that returns 500 documents costs 500 reads each time it changes; use limit() and pagination. Third, model the data for your queries: Firestore has no joins, so you often duplicate a field (such as the author's name) rather than fetch two documents.

The Realtime Database looks different, because everything is one JSON tree addressed by path:

Kotlin
// read-only example: Realtime Database
val ref = Firebase.database.getReference("presence/${auth.currentUser!!.uid}")
ref.setValue(true)                                // write
ref.onDisconnect().setValue(false)                // the server runs this when the client drops

ref.addValueEventListener(object : ValueEventListener {
    override fun onDataChange(snapshot: DataSnapshot) {
        val online = snapshot.getValue(Boolean::class.java) ?: false
    }
    override fun onCancelled(error: DatabaseError) { /* rules denied it, or the listener was removed */ }
})

Why listeners and offline matter

Both databases keep a local cache, so a listener first fires from the cache and again when the server confirms. A write you make is applied locally at once, so your UI updates instantly, and is sent when the network is available. If the server rejects it (the rules say no), the local change is rolled back and an error is reported. That model is similar to the offline-first design in Errors and Offline-First.

The second stand-in models a document store with queries and live listeners. It is not Firestore, only the idea: collections of documents, a query that re-delivers its results on every change, and unsubscribing.

Kotlin A document store with live queries (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Security rules

Because your app talks to the database directly, the rules you write in the Firebase console (or firestore.rules) are the server-side check on every read and write. A client can be modified, so never trust "the app only does the right thing".

TEXT
// read-only example: firestore.rules
rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {

    match /notes/{noteId} {
      // Only the owner can read; only signed-in users can create their own notes
      allow read: if request.auth != null && resource.data.ownerId == request.auth.uid;
      allow create: if request.auth != null
                    && request.resource.data.ownerId == request.auth.uid
                    && request.resource.data.title is string
                    && request.resource.data.title.size() <= 200;
      allow update, delete: if request.auth != null && resource.data.ownerId == request.auth.uid;
    }
  }
}

Read it as: request.auth is the signed-in user (null for anonymous callers), resource.data is the stored document and request.resource.data is the document the client wants to write. The rules above check that the caller owns the note, that the new note names them as the owner, and that the title is a short string. A very common beginner mistake is test mode, which opens the whole database for a limited time. Never ship with allow read, write: if true. Use the Firebase Emulator Suite and the rules unit-testing library to test rules locally.

Remember that queries must be allowed as a whole: Firestore does not filter documents after the fact. A query for notes without whereEqualTo("ownerId", uid) is rejected, because it could return documents the user may not read. The third stand-in models a rules check.

Kotlin A security rules check (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Push notifications with FCM

Firebase Cloud Messaging (FCM) delivers messages from a server to a device, even if the app is closed. The detailed behavior of notification messages versus data messages, channels and the POST_NOTIFICATIONS permission is in Services, Notifications and Foreground Work. Here is the Firebase side of it.

  1. Add firebase-messaging and declare a FirebaseMessagingService in the manifest (the service code is in the other lesson).
  2. On Android 13+, ask for POST_NOTIFICATIONS in context.
  3. Get the registration token and send it to your backend together with the user ID. Tokens change, so update on onNewToken too.
Kotlin
// read-only example: fetch the token and register it
suspend fun registerPushToken(userId: String) {
    val token = Firebase.messaging.token.await()
    Firebase.firestore.collection("users").document(userId)
        .set(mapOf("fcmTokens" to FieldValue.arrayUnion(token)), SetOptions.merge())
        .await()
}

The server (a Cloud Function, or your own backend with the Firebase Admin SDK) then sends to a token, or to a topic that clients subscribe to (Firebase.messaging.subscribeToTopic("news")), which suits broadcast messages without keeping a list of tokens. Topic subscriptions are not secret, so do not use them for private data.

The last stand-in keeps a token registry the way a backend does, including pruning tokens that FCM reports as unregistered.

Kotlin Token registry and sending (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Crashlytics, Analytics and the rest

Firebase has many other services. Two are useful in nearly every app:

  • Crashlytics collects crashes and non-fatal errors with stack traces, device and OS details, and groups them. You add the plugin and the library, and it hooks the uncaught exception handler. Upload mapping files automatically for R8-minified release builds so traces are readable, and add Firebase.crashlytics.setUserId(...) or custom keys to see context. Do not log personal data.
  • Analytics records events (screen views, purchases, custom events) for funnels and audiences. It collects data about users, so follow the privacy rules of your stores and regions, ask for consent where it is required, and document it in the Play Console data safety form.

Others you will meet are Remote Config (change values without a release), Cloud Storage for Firebase (user uploads), Cloud Functions (server code), App Check (verifies requests come from your genuine app) and App Distribution (testers). Each one is another dependency, another place where data goes, and another bill, so add them deliberately.

Phone number sign-in and on-device ML

Phone sign-in (OTP). Firebase Authentication can sign users in with a one-time code sent by SMS. The flow has two steps and a few states you must handle:

  1. Call PhoneAuthProvider.verifyPhoneNumber with the number in international format (+49...) and a callback.
  2. The callback ends in one of three ways: onVerificationCompleted (the SMS was auto-detected or instantly verified, so you get a credential and can sign in), onCodeSent (you receive a verificationId and show a code field) or onVerificationFailed (invalid number, quota exceeded, no network).
  3. When the user types the six-digit code, create PhoneAuthProvider.getCredential(verificationId, code) and call auth.signInWithCredential(credential).
Kotlin
// read-only example: the two steps
fun sendCode(activity: Activity, phone: String) {
    val options = PhoneAuthOptions.newBuilder(Firebase.auth)
        .setPhoneNumber(phone)
        .setTimeout(60L, TimeUnit.SECONDS)
        .setActivity(activity)
        .setCallbacks(object : PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
            override fun onVerificationCompleted(credential: PhoneAuthCredential) { signIn(credential) }
            override fun onVerificationFailed(e: FirebaseException) { showError(e.localizedMessage) }
            override fun onCodeSent(id: String, token: PhoneAuthProvider.ForceResendingToken) {
                verificationId = id                      // keep it: you need it with the code
                showCodeField()
            }
        })
        .build()
    PhoneAuthProvider.verifyPhoneNumber(options)
}

fun verify(code: String) = signIn(PhoneAuthProvider.getCredential(verificationId, code))

Keep the verificationId in your ViewModel so a rotation does not lose it, validate the number format before calling, offer a "resend code" button after a delay, and expect SMS to cost money at scale (Firebase has free and paid quotas). Test numbers configured in the console let you develop without sending real messages. Prefer a second factor over SMS alone for sensitive accounts, since SMS can be intercepted.

FirebaseUI Auth is a prebuilt sign-in screen that handles email, phone and federated providers for you; it is the fastest way to get a working login, at the cost of less control over the design.

On-device machine learning is a separate product from Firebase's cloud services: ML Kit runs models on the phone for face detection, barcode scanning, text recognition, image labeling and translation. Because the work happens on the device it is fast, works offline and keeps the camera image private. A face-detection screen follows the same shape as the QR scanner in Utility apps: CameraX supplies frames, the ML Kit client processes each one asynchronously, and you draw the results (bounding boxes, smile probability) over the preview. Always close each frame when processing completes, ask for the CAMERA permission at run time and tell users what you do with face data, because regulations treat it as sensitive.

When Firebase is the wrong choice

Firebase is quick to start and has fewer moving parts. The costs show up later: data lives in a proprietary model that is awkward to export or move; the Firestore pricing model rewards careful reads; complex relational queries and reports are not a fit; and your app depends on Google services that are missing on some devices (Huawei phones without Play services, for example). If you need SQL, long-term portability or heavy reporting, put a normal backend behind Retrofit and use Room for local data.

Common mistakes

  • Shipping with test-mode rules. Anyone with your project ID can read or erase the data.
  • Forgetting the debug and release SHA fingerprints. Google sign-in works in debug and fails in release.
  • Never removing snapshot listeners. The screen is gone, but you keep paying for reads and leaking memory.
  • Loading whole collections. Use limit(), queries and pagination.
  • Trusting client-side checks. Anything the client does must be repeated in rules.
  • Treating FCM tokens as permanent. Refresh them on onNewToken, and prune dead tokens.
  • Putting Firebase types in the UI layer. Wrap them in a repository so you can test and replace them.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does the Firebase BoM do?

    The Bill of Materials is a platform dependency that fixes versions for all Firebase libraries you add, so they work together.
  2. 2. Which database fits most new apps with structured data and filtered queries?

    Firestore offers richer queries, automatic scaling and clear rules. The Realtime Database suits very frequent small updates such as presence.
  3. 3. A user opens your app and changes a Firestore document while offline. What happens?

    Firestore applies writes to its local cache first and syncs them later. If the server's rules reject it, the change is rolled back.
  4. 4. Why are security rules essential in a Firebase app?

    There is no backend of your own to enforce permissions. A modified client could send any request, so the rules must decide.
  5. 5. Your server tries to push to an old FCM token and gets UNREGISTERED. What should it do?

    Tokens change after reinstalls and other events. Prune dead tokens and store the new one that the app sends from onNewToken.

Summary

  • Firebase provides managed backend services: add the BoM, the Google Services plugin and google-services.json for your package name and signing fingerprints.
  • Firebase Authentication handles accounts; wrap it in a repository, expose a Flow of auth state and keep Firebase types out of the UI.
  • Firestore (documents and indexed queries) fits most apps; the Realtime Database (one JSON tree) fits frequent, low-latency updates; both sync and work offline.
  • Always remove snapshot listeners, limit reads and design data for your queries, since there are no joins.
  • Security rules are your only server-side control, so write them, test them with the emulator and never ship test mode.
  • FCM needs a registration token sent to your backend, onNewToken handling, and the channel and permission rules from the notifications lesson.
  • Crashlytics and Analytics are the common extras; weigh Firebase's lock-in and costs before choosing it.
  • The Android and Firebase code is read-only; the TryIts are stand-ins for auth state, a document store with live queries, rules and a token registry.

Next: Dependency Injection Concepts