Firebase is Google's backend for apps. It gives you accounts, a database, file storage, push notifications and monitoring without running your own server. It is a quick way to build real-time apps such as the chat project. Its services and screens change often, so use the current Firebase documentation for setup steps and treat this lesson as the map.
Set up a Firebase project
- Open the Firebase console and create a project.
- Add an Android app with your application ID (the one from
build.gradle.kts). - Download
google-services.jsonand place it in theappfolder. Add it to.gitignoreif your repository is public and you are not ready to share the project details. - Add the Google services Gradle plugin and the Firebase BoM, then the libraries you need, for example
firebase-auth,firebase-firestore,firebase-storage,firebase-messaging,firebase-analytics,firebase-crashlytics,firebase-config. - Sync, run, and check the console for the first connection.
Authentication
- Email and password:
Firebase.auth.createUserWithEmailAndPasswordandsignInWithEmailAndPassword. Send a verification email and a password-reset email. - Google Sign-In: use the Credential Manager API to get a Google ID token and exchange it with
GoogleAuthProvider.getCredential. - Phone number: sends an SMS code, and needs setup of SHA fingerprints and, in testing, test numbers.
- Read the signed-in user with
Firebase.auth.currentUseror a listener, and sign out withsignOut().
suspend fun signIn(email: String, password: String): Result<String> = try {
val result = Firebase.auth.signInWithEmailAndPassword(email, password).await()
Result.success(result.user?.uid.orEmpty())
} catch (e: Exception) {
Result.failure(e)
}
await() comes from the kotlinx-coroutines-play-services library and turns a Firebase Task into a suspend call.
Cloud Firestore and Realtime Database
Firestore stores *documents* (like JSON objects) in *collections*. It supports queries and live listeners and works offline with a local cache. The Realtime Database is an older, simpler JSON tree, good for very small, fast data. For most new apps choose Firestore.
val db = Firebase.firestore
// write
db.collection("rooms").document(roomId).collection("messages")
.add(mapOf("text" to text, "from" to uid, "at" to FieldValue.serverTimestamp()))
// live updates as a Flow
fun messages(roomId: String): Flow<List<Message>> = callbackFlow {
val reg = db.collection("rooms").document(roomId).collection("messages")
.orderBy("at")
.addSnapshotListener { snap, _ ->
trySend(snap?.toObjects(Message::class.java).orEmpty())
}
awaitClose { reg.remove() }
}
Storage, push messaging and monitoring
- Cloud Storage: upload images and files with
Firebase.storage.reference.child(path).putFile(uri)and get a download URL. - Cloud Messaging (FCM): the server (or the console) sends a push message to a device token. Your
FirebaseMessagingServicereceives data messages; notification messages are shown by the system when the app is in the background. On Android 13 and later the user must allow notifications. - Analytics: log events like
purchaseorsign_upto see how people use the app. - Crashlytics: collects crash reports with stack traces from real devices.
- Remote Config: change values (a banner text, a feature flag) without a new release.
- Performance Monitoring: measures startup time and network calls.
- App Distribution: sends test builds to testers.
Security rules and App Check
Anyone can read your app's google-services.json, so the database is protected only by security rules. Write rules that require sign-in and limit each user to their own data. Never leave test-mode rules (open to everyone) on a live project. App Check adds a check that requests come from your genuine app.
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /users/{userId} {
allow read, write: if request.auth != null && request.auth.uid == userId;
}
match /rooms/{roomId}/messages/{msgId} {
allow read: if request.auth != null;
allow create: if request.auth != null && request.resource.data.from == request.auth.uid;
}
}
}
Your task
- Create a Firebase project, connect an app and sign in with email and password.
- Write a message to Firestore and see it appear in the console.
- Add a listener and show messages live on two devices.
- Write security rules and test them in the Firebase Rules Playground.
How to check it worked
- Only signed-in users can read messages.
- Messages appear on a second device without a refresh.
- You know why test-mode rules are unsafe.