0
0
Android Kotlinmobile~15 mins

Cloud Messaging (push notifications) in Android Kotlin - Deep Dive

Choose your learning style9 modes available
Overview - Cloud Messaging (push notifications)
What is it?
Cloud Messaging, often called push notifications, lets apps receive messages from servers even when the app is not open. These messages can show alerts, update content, or trigger actions on the device. It works by sending data from a cloud service to the user's device through a messaging system.
Why it matters
Without cloud messaging, apps would have to constantly check for updates themselves, which wastes battery and data. Push notifications keep users informed instantly and help apps stay interactive and useful. They are essential for timely alerts like messages, reminders, or news.
Where it fits
Before learning cloud messaging, you should understand basic Android app development and networking concepts. After this, you can explore advanced notification customization, background processing, and integrating messaging with app analytics.
Mental Model
Core Idea
Cloud messaging is a way for servers to send instant messages to apps on devices, waking them up or notifying users without the app running actively.
Think of it like...
It's like a postal service that delivers letters directly to your mailbox at home, even if you're not there, so you get important news as soon as it arrives.
┌───────────────┐      ┌───────────────┐      ┌───────────────┐
│   Server /    │─────▶│ Cloud Messaging│─────▶│ User's Device │
│  App Backend  │      │   Service     │      │   (App)       │
└───────────────┘      └───────────────┘      └───────────────┘
Build-Up - 7 Steps
1
FoundationWhat Are Push Notifications
🤔
Concept: Introduction to what push notifications are and how they differ from regular app messages.
Push notifications are messages sent from a server to a user's device to alert or inform them. Unlike messages inside the app, push notifications can appear even if the app is closed or the phone is locked.
Result
You understand that push notifications are a way to reach users instantly without them opening the app.
Knowing that push notifications work outside the app's active state explains why they are powerful for user engagement.
2
FoundationBasic Components of Cloud Messaging
🤔
Concept: Learn the main parts involved: the app, the cloud messaging service, and the server.
There are three parts: the app on the device, the cloud messaging service (like Firebase Cloud Messaging), and the server that sends messages. The server tells the cloud service what to send, and the cloud service delivers it to the app.
Result
You can identify the roles of each part in the messaging process.
Understanding these roles helps you see how messages flow from server to device.
3
IntermediateSetting Up Firebase Cloud Messaging
🤔Before reading on: do you think you need to write code first or configure services first? Commit to your answer.
Concept: Learn how to connect your Android app to Firebase to enable cloud messaging.
You start by creating a Firebase project, adding your Android app to it, and downloading a configuration file (google-services.json). Then, you add Firebase dependencies to your app's build files to enable messaging features.
Result
Your app is registered with Firebase and ready to receive messages.
Knowing that configuration comes before coding prevents confusion and setup errors.
4
IntermediateReceiving Messages in the App
🤔Before reading on: do you think the app receives messages automatically or needs code to handle them? Commit to your answer.
Concept: Learn how to write code to handle incoming messages and show notifications.
You create a service that extends FirebaseMessagingService and override onMessageReceived to handle messages. You can extract data and show a notification using NotificationManager.
Result
Your app can receive and display push notifications when messages arrive.
Understanding that the app must handle messages lets you customize notifications and app behavior.
5
IntermediateSending Messages from Server
🤔Before reading on: do you think messages are sent directly from app to app or through a server? Commit to your answer.
Concept: Learn how servers send messages to devices using Firebase Cloud Messaging APIs.
Servers use Firebase Cloud Messaging HTTP API or SDKs to send messages. They include the device token and message data. Firebase then routes the message to the correct device.
Result
You understand how to trigger push notifications from your backend.
Knowing the server role clarifies how messages reach the right device securely.
6
AdvancedHandling Message Types and App States
🤔Before reading on: do you think all messages behave the same regardless of app state? Commit to your answer.
Concept: Learn the difference between notification and data messages and how app state affects message handling.
Notification messages are displayed by the system when the app is backgrounded. Data messages are handled by the app code and can trigger custom actions. Behavior changes if the app is foregrounded, backgrounded, or killed.
Result
You can design message payloads to control user experience depending on app state.
Understanding message types and app states helps avoid missed notifications or unwanted behavior.
7
ExpertOptimizing Delivery and Battery Use
🤔Before reading on: do you think push notifications always arrive instantly? Commit to your answer.
Concept: Learn how message priority, batching, and device conditions affect delivery timing and battery consumption.
Firebase Cloud Messaging uses message priority to decide delivery speed. High priority wakes the device immediately but uses more battery. Normal priority may delay delivery to save power. Understanding this helps balance user experience and battery life.
Result
You can configure messages to optimize for timely alerts or battery saving.
Knowing delivery trade-offs prevents user complaints about delayed or excessive notifications.
Under the Hood
When a server sends a message, it calls Firebase Cloud Messaging (FCM) APIs with the device's registration token. FCM authenticates the request and queues the message. It then uses Google Play services on the device to deliver the message via a persistent connection. The device wakes the app or system UI depending on message type and app state.
Why designed this way?
This design centralizes message routing in a reliable cloud service, reducing device battery use by avoiding constant polling. Using Google Play services ensures efficient, secure delivery across many device models and Android versions.
┌───────────────┐
│   App Server  │
└──────┬────────┘
       │ Send message with token
       ▼
┌───────────────┐
│ Firebase Cloud│
│  Messaging    │
└──────┬────────┘
       │ Deliver via persistent connection
       ▼
┌───────────────┐
│ Google Play   │
│ Services      │
└──────┬────────┘
       │ Wake app or show notification
       ▼
┌───────────────┐
│ Android Device│
│    App        │
└───────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Do push notifications always arrive instantly on any device? Commit to yes or no.
Common Belief:Push notifications are always delivered instantly and reliably.
Tap to reveal reality
Reality:Delivery depends on device state, network, and message priority. Sometimes messages are delayed or dropped to save battery.
Why it matters:Expecting instant delivery can cause confusion and poor user experience if messages arrive late or not at all.
Quick: Can your app receive push notifications without registering with Firebase? Commit to yes or no.
Common Belief:Apps can receive push notifications without any cloud service registration.
Tap to reveal reality
Reality:Apps must register with a cloud messaging service like Firebase to get a unique token for receiving messages.
Why it matters:Skipping registration means the app cannot receive messages, breaking notification features.
Quick: Do notification messages always trigger app code when received? Commit to yes or no.
Common Belief:All push notifications run app code when they arrive.
Tap to reveal reality
Reality:Notification messages are handled by the system when the app is backgrounded and may not run app code immediately.
Why it matters:Assuming app code runs can lead to missed updates or logic errors.
Quick: Is it safe to send sensitive data in push notification payloads? Commit to yes or no.
Common Belief:Push notification payloads are secure and can contain sensitive data safely.
Tap to reveal reality
Reality:Push notifications are not encrypted end-to-end and can be intercepted; sensitive data should be avoided or encrypted separately.
Why it matters:Sending sensitive data insecurely risks user privacy and security breaches.
Expert Zone
1
Message token rotation happens periodically; apps must handle token refresh to maintain delivery.
2
Using data messages allows silent updates without user disturbance, useful for background syncing.
3
Combining push notifications with analytics helps optimize user engagement and notification strategy.
When NOT to use
Cloud messaging is not suitable for real-time communication requiring guaranteed delivery like live chat; use WebSockets or real-time databases instead.
Production Patterns
In production, apps use topic subscriptions to send group messages, handle token refresh gracefully, and implement fallback logic for message failures.
Connections
Event-driven Architecture
Cloud messaging builds on event-driven principles where servers emit events (messages) that apps react to asynchronously.
Understanding event-driven systems helps grasp how push notifications trigger app behavior without polling.
Battery Management in Mobile Devices
Cloud messaging delivery respects battery management policies by adjusting message priority and delivery timing.
Knowing battery management explains why some notifications are delayed or batched.
Postal Mail System
Push notifications resemble postal mail delivery where messages are sent to a mailbox and retrieved when the recipient is available.
This connection clarifies asynchronous message delivery and the role of intermediaries.
Common Pitfalls
#1Not handling token refresh leads to lost messages.
Wrong approach:override fun onNewToken(token: String) { // No code to update server with new token }
Correct approach:override fun onNewToken(token: String) { sendTokenToServer(token) }
Root cause:Ignoring that device tokens can change causes the server to send messages to old tokens.
#2Sending large payloads causes message delivery failure.
Wrong approach:val message = RemoteMessage.Builder(token) .setData(mapOf("key" to "very large data string...")) .build()
Correct approach:Send minimal data in push and fetch large content from server after notification tap.
Root cause:Misunderstanding payload size limits leads to dropped messages.
#3Assuming notification messages always trigger app code.
Wrong approach:override fun onMessageReceived(message: RemoteMessage) { // Expect this to run for all notifications }
Correct approach:Use data messages for guaranteed app code execution; notification messages may be handled by system.
Root cause:Confusing notification and data message behavior causes missed app logic.
Key Takeaways
Cloud messaging enables apps to receive messages instantly from servers even when not running.
It relies on a cloud service like Firebase to route messages securely and efficiently.
Apps must register and handle messages properly to show notifications and update content.
Message delivery depends on device state and priority, balancing immediacy and battery life.
Understanding token management, message types, and server integration is key for reliable push notifications.