Firebase is Google's mobile and web development platform providing backend services — authentication, NoSQL databases, file storage, analytics, and cloud messaging — without managing your own servers.
Connect your Android app to a Firebase project in a few steps. The Firebase console generates a google-services.json config file that links your app to backend services.
Firebase Authentication supports email/password, Google Sign-In, phone OTP, and more. It handles secure token management and integrates with Firestore security rules.
Email/password sign up and login
Kotlin — AuthRepository.ktclass AuthRepository {
private val auth = FirebaseAuth.getInstance()
val currentUser: FirebaseUser? get() = auth.currentUser
val isLoggedIn: Boolean get() = currentUser != null
suspend fun signUp(email: String, password: String): Result<FirebaseUser> {
return try {
val result = auth.createUserWithEmailAndPassword(email, password).await()
Result.success(result.user!!)
} catch (e: Exception) {
Result.failure(e)
}
}
suspend fun signIn(email: String, password: String): Result<FirebaseUser> {
return try {
val result = auth.signInWithEmailAndPassword(email, password).await()
Result.success(result.user!!)
} catch (e: Exception) {
Result.failure(e)
}
}
fun signOut() = auth.signOut()
}
Login Activity usage
Kotlin — LoginActivity.ktclass LoginActivity : AppCompatActivity() {
private val authRepo = AuthRepository()
private fun login() {
val email = binding.etEmail.text.toString().trim()
val password = binding.etPassword.text.toString()
lifecycleScope.launch {
binding.btnLogin.isEnabled = false
val result = authRepo.signIn(email, password)
binding.btnLogin.isEnabled = true
result.onSuccess {
startActivity(Intent(this@LoginActivity, MainActivity::class.java))
finish()
}.onFailure { e ->
Toast.makeText(this@LoginActivity, e.message, Toast.LENGTH_SHORT).show()
}
}
}
}
Firebase Realtime Database stores data as a JSON tree and syncs changes to all connected clients in milliseconds — ideal for chat apps and live leaderboards.
Write and read data
Kotlin — Realtime Database CRUDclass ChatRepository {
private val database = FirebaseDatabase.getInstance()
private val messagesRef = database.getReference("messages")
fun sendMessage(userId: String, text: String) {
val key = messagesRef.push().key ?: return
val message = mapOf(
"id" to key,
"userId" to userId,
"text" to text,
"timestamp" to ServerValue.TIMESTAMP
)
messagesRef.child(key).setValue(message)
}
fun listenForMessages(onMessages: (List<ChatMessage>) -> Unit) {
messagesRef.orderByChild("timestamp").addValueEventListener(object : ValueEventListener {
override fun onDataChange(snapshot: DataSnapshot) {
val messages = snapshot.children.mapNotNull { child ->
child.getValue(ChatMessage::class.java)
}
onMessages(messages)
}
override fun onCancelled(error: DatabaseError) {
Log.e("RTDB", "Listen failed", error.toException())
}
})
}
}
data class ChatMessage(
val id: String = "",
val userId: String = "",
val text: String = "",
val timestamp: Long = 0
)
Firestore vs Realtime Database: Prefer Firestore for new projects (better queries, scaling, offline). Use Realtime Database when you need ultra-low-latency sync with a simple JSON tree.
4Firestore
Cloud Firestore is a flexible, scalable NoSQL document database. Data is organized in collections and documents with powerful querying and offline support.
Add, read, update, delete
Kotlin — FirestoreRepository.ktclass FirestoreRepository {
private val db = FirebaseFirestore.getInstance()
private val usersRef = db.collection("users")
suspend fun addUser(user: User): String {
val docRef = usersRef.add(user).await()
return docRef.id
}
suspend fun getUser(userId: String): User? {
val snapshot = usersRef.document(userId).get().await()
return snapshot.toObject(User::class.java)
}
suspend fun updateUser(userId: String, name: String) {
usersRef.document(userId)
.update("name", name, "updatedAt", FieldValue.serverTimestamp())
.await()
}
suspend fun deleteUser(userId: String) {
usersRef.document(userId).delete().await()
}
}
data class User(
val name: String = "",
val email: String = "",
val createdAt: Timestamp? = null
)
Firebase Console — storage.rulesrules_version = '2';
service firebase.storage {
match /b/{bucket}/o {
match /profile_images/{userId}.jpg {
allow read: if request.auth != null;
allow write: if request.auth != null && request.auth.uid == userId;
}
}
}
6Push Notifications
Firebase Cloud Messaging (FCM) delivers push notifications to Android devices. Messages can be sent from the Firebase Console, your backend server, or Cloud Functions.
FirebaseMessagingService
Kotlin — MyFirebaseMessagingService.ktclass MyFirebaseMessagingService : FirebaseMessagingService() {
override fun onMessageReceived(message: RemoteMessage) {
super.onMessageReceived(message)
val title = message.notification?.title ?: message.data["title"] ?: "Notification"
val body = message.notification?.body ?: message.data["body"] ?: ""
showNotification(title, body, message.data)
}
override fun onNewToken(token: String) {
super.onNewToken(token)
Log.d("FCM", "Refreshed token: $token")
sendRegistrationToServer(token)
}
private fun showNotification(title: String, body: String, data: Map<String, String>) {
val channelId = "fcm_default"
val intent = Intent(this, MainActivity::class.java).apply {
flags = Intent.FLAG_ACTIVITY_CLEAR_TOP
data.forEach { (key, value) -> putExtra(key, value) }
}
val pendingIntent = PendingIntent.getActivity(
this, 0, intent,
PendingIntent.FLAG_ONE_SHOT or PendingIntent.FLAG_IMMUTABLE
)
val notification = NotificationCompat.Builder(this, channelId)
.setSmallIcon(R.drawable.ic_notification)
.setContentTitle(title)
.setContentText(body)
.setAutoCancel(true)
.setContentIntent(pendingIntent)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.build()
NotificationManagerCompat.from(this).notify(System.currentTimeMillis().toInt(), notification)
}
}
Kotlin — Get FCM tokenFirebaseMessaging.getInstance().token.addOnCompleteListener { task ->
if (task.isSuccessful) {
val token = task.result
Log.d("FCM", "Token: $token")
// Save to Firestore under users/{uid}/fcmToken
}
}
Send from Firebase Console
Firebase Console → Engage → Messaging
Click Create campaign → Notifications
Enter title, body, and target (all users or topic)
Publish — devices with your app receive the notification
Data vs notification payload
Payload Type
Handled By
When App in Background
notification
System tray automatically
System shows notification
data
onMessageReceived()
Your code handles display
Both
System + your handler
System shows; tap opens app with data
7Hands-On Exercises
1
Create a Firebase project, add your Android app, and complete Firebase Setup with BOM dependencies.
2
Build email/password sign up and login screens. Redirect to MainActivity when authenticated.
3
Create a simple chat using Realtime Database — send messages and display them in real time.
4
Build a todo app with Firestore: add, list, mark complete, and delete todos with a real-time listener.
5
Upload a profile photo to Firebase Storage and save the download URL in the user's Firestore document.
6
Implement FCM: log the device token, handle incoming messages in FirebaseMessagingService, and show a local notification.
7
Bonus: Send a test push from Firebase Console and verify the notification appears on your device.
Firebase MCQ Practice
10 Basic MCQs10 Advanced MCQs
10 Basic Firebase MCQs
1
Firebase is?
ALinux kernel fork
BGoogle mobile/backend platform (BaaS)
CLayout editor
DGradle replacement
Explanation: Auth, Firestore, Storage, FCM, Analytics, and more.
2
google-services.json placed in?
Aassets only
BManifest folder
CApp module root directory
DGradle wrapper
Explanation: Downloaded from Firebase console per app.
3
Firebase Authentication supports?
ACamera only
BSQL only
CBluetooth only
DEmail, Google, phone, anonymous
Explanation: Multiple sign-in providers via Firebase Auth SDK.
4
Cloud Firestore stores?
ANoSQL document data in collections
BRelational SQL tables locally only
CAPK files
DLayout XML
Explanation: Documents in collections with real-time sync.
5
Realtime Database vs Firestore?
AIdentical
BFirestore newer with richer queries and scaling
CRTDB only option
DBoth SQL
Explanation: Firestore recommended for new projects.
6
Firebase Storage for?
ADex files
BLocal SQLite
CUser files — images, videos in cloud
DEmulator images
Explanation: Backed by Google Cloud Storage buckets.
7
FCM token used to?
ALayout preview
BSign APK
CCompile Kotlin
DTarget device for push messages
Explanation: Server sends messages to device token via FCM API.
8
Firebase BOM in Gradle?
ABill of Materials aligning Firebase library versions