This course will cover how to receive push notifications from a server in Android apps using Kotlin. Mobile applications often provide users with real-time information, making push notifications play a crucial role in enhancing user experience. Through this course, you will learn how to implement push notifications in Android apps using Firebase Cloud Messaging (FCM).
1. Introduction to Firebase Cloud Messaging (FCM)
Firebase Cloud Messaging (FCM) is a service provided by Google that helps app developers send messages to users in real-time. This service is primarily used for sending notifications, and messages can include text, images, videos, and more.
Main Features of FCM
- Messages can be sent from the server to the client.
- Messages can be sent both when users are using the app and when they are not.
- Supports topic-based messaging.
2. Project Setup
Let’s go through the process of creating a new project in Android Studio and setting up FCM.
2.1 Setting up Firebase Console
- Log in to Firebase Console.
- Create a new project and enter the project name.
- Add the app as Android. Enter the package name and add the SHA-1 key.
- Download the google-services.json file and add it to the app folder of the Android app.
2.2 Gradle Setup
Add the necessary dependencies to the app’s build.gradle file:
dependencies {
implementation 'com.google.firebase:firebase-messaging-ktx:23.1.0' // Check for the latest version
}
And add the following to the project’s build.gradle file to apply the Google services plugin:
buildscript {
dependencies {
classpath 'com.google.gms:google-services:4.3.10'
}
}
2.3 Manifest Setup
Set up the FCM service in the AndroidManifest.xml file:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.myapp">
<application
... >
<service
android:name=".MyFirebaseMessagingService">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT"/>
</intent-filter>
</service>
</application>
</manifest>
3. Implementing FCM Messaging Service
Now let’s implement the MyFirebaseMessagingService class to receive messages via FCM.
3.1 MyFirebaseMessagingService Class
To receive push notifications, create the MyFirebaseMessagingService class that inherits from FirebaseMessagingService:
import android.app.NotificationChannel
import android.app.NotificationManager
import android.content.Context
import android.os.Build
import android.util.Log
import com.google.firebase.messaging.FirebaseMessagingService
import com.google.firebase.messaging.RemoteMessage
class MyFirebaseMessagingService : FirebaseMessagingService() {
override fun onMessageReceived(remoteMessage: RemoteMessage) {
// Message receive logic
Log.d("FCM", "From: ${remoteMessage.from}")
remoteMessage.notification?.let {
sendNotification(it.title, it.body)
}
}
private fun sendNotification(title: String?, messageBody: String?) {
val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
val channelId = "default_channel"
val builder = NotificationCompat.Builder(this, channelId)
.setSmallIcon(R.drawable.ic_notification)
.setContentTitle(title)
.setContentText(messageBody)
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val channel = NotificationChannel(channelId, "Channel human-readable title", NotificationManager.IMPORTANCE_DEFAULT)
notificationManager.createNotificationChannel(channel)
}
notificationManager.notify(0, builder.build())
}
}
4. Sending Messages from the Server
Now let’s look at how to send messages from the server via FCM. We send a POST request using the FCM API to send messages.
4.1 Server Code Example
Below is an example of sending messages to FCM from a server using Node.js:
const express = require('express');
const admin = require('firebase-admin');
const app = express();
admin.initializeApp({
credential: admin.credential.applicationDefault(),
databaseURL: 'https://.firebaseio.com'
});
app.post('/send', (req, res) => {
const message = {
notification: {
title: 'Hello!',
body: 'You have received a new message.'
},
token: ''
};
admin.messaging().send(message)
.then(response => {
res.send('Successfully sent message: ' + response);
})
.catch(error => {
console.error('Error sending message:', error);
res.status(500).send('Error sending message');
});
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
5. Testing Push Notification Reception
After setting up the mobile app and the server, let’s test the reception of push notifications. Run the app in Android Studio and send a POST request to the server to send a push notification. When the user receives the notification, it should be displayed through the NotificationChannel set in the app.
6. Optimization and Cautions
When integrating push notifications into your service, keep the following points in mind:
- You need to request permission for users to receive notifications.
- You should ensure that the content of push notifications is meaningful and that users do not receive unwanted information.
- Be careful with token management (e.g., re-registration) when sending messages.
Conclusion
In this course, we explored how to receive push notifications sent from the server to an Android app using Firebase Cloud Messaging (FCM). Utilizing FCM can strengthen communication with users and greatly enhance app usability. Based on what you have learned in this course, try developing more advanced applications.