In this tutorial, we will explain in detail how to implement push notifications within an Android application using Firebase Cloud Messaging (FCM). FCM is a cloud service provided by Google that enables mobile applications to send messages to users.
1. Introduction to Firebase Cloud Messaging (FCM)
Firebase Cloud Messaging (FCM) is a free service that allows developers to send messages between servers and client apps.
With FCM, tasks such as sending push notifications, transferring messages between devices, or sending data messages can be carried out easily.
1.1 Key Features of FCM
- Supports push notifications for free.
- Supports various platforms including Android, iOS, and web.
- Allows detailed configuration for message sending.
- Supports notification handling in the background.
2. Setting Up Firebase Project
To use FCM, you need to create a Firebase project.
Follow the steps below to set up your Firebase project.
2.1 Accessing Firebase Console
1. Go to the Firebase Console.
2. Log in with your Google account.
3. Click the “Add Project” button to create a new project.
2.2 Activating Firebase Cloud Messaging
1. In the Firebase project dashboard, select “Cloud Messaging.”
2. Verify the server key and sender ID, which will be needed for integration with the Android app later.
3. Setting Up Android Studio Project
▶ Next, we will learn how to integrate Firebase into the Android project.
3.1 Installing Android Studio
Install Android Studio and create a new project.
Set the minimum SDK version and project language to Java before starting development.
3.2 Integrating Firebase
1. In Android Studio, select the “Tools” menu and click on “Firebase.”
2. When the Firebase Assistant opens, find “Cloud Messaging” and click on “Set up Firebase Cloud Messaging.”
3. The Firebase SDK will be automatically added to your project.
3.3 Gradle Configuration
You need to add the necessary dependencies in the build.gradle (Module: app)
file.
dependencies {
implementation 'com.google.firebase:firebase-messaging:23.0.0' // Change version to the latest
}
3.4 AndroidManifest.xml Configuration
Add configurations to the Android manifest file to enable the use of FCM.
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.fcmexample">
<application
...
>
<service
android:name=".MyFirebaseMessagingService"
android:exported="false">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT"/>
</intent-filter>
</service>
</application>
</manifest>
4. Implementing FCM Message Reception
To receive FCM messages, you need to implement a class that inherits from FirebaseMessagingService.
4.1 Implementing FirebaseMessagingService
Create a class for receiving messages and override the onMessageReceived method.
This method is called when a push notification is received.
import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;
public class MyFirebaseMessagingService extends FirebaseMessagingService {
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
// Code for receiving messages
if (remoteMessage.getNotification() != null) {
// Show notification
showNotification(remoteMessage.getNotification().getTitle(),
remoteMessage.getNotification().getBody());
}
}
private void showNotification(String title, String message) {
// Use NotificationManager to display the notification
}
}
5. Sending Messages
Now let’s learn how to send messages from the server using FCM.
We will implement a Node.js server to send messages and learn how to handle errors in the client app.
5.1 Setting Up Node.js Server
Set up a simple server using Node.js to send messages via FCM.
First, install the necessary packages.
npm install firebase-admin
5.2 Server Code
const admin = require('firebase-admin');
// Initialize Firebase Admin SDK
admin.initializeApp({
credential: admin.credential.applicationDefault(),
});
const fcmToken = 'YOUR_DEVICE_TOKEN'; // FCM token of the device to send the message
const message = {
notification: {
title: 'Hello!',
body: 'This is a test notification.',
},
token: fcmToken,
};
// Sending the message
admin.messaging().send(message)
.then((response) => {
console.log('Successfully sent message:', response);
})
.catch((error) => {
console.log('Error sending message:', error);
});
6. Implementing Notification Display
To show the received messages to the user, display a notification.
You can create notifications using NotificationCompat.
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.os.Build;
private void showNotification(String title, String message) {
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
String channelId = "Channel_ID";
String channelName = "Channel_Name";
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_DEFAULT);
notificationManager.createNotificationChannel(channel);
}
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, channelId)
.setSmallIcon(R.drawable.ic_notification)
.setContentTitle(title)
.setContentText(message)
.setPriority(NotificationCompat.PRIORITY_DEFAULT);
notificationManager.notify(1, builder.build());
}
7. Testing Push Notifications
Run the server to check if the message is sent to the device with the designated FCM token.
After sending, run the Android app to verify if the notification appears.
8. Conclusion
In this tutorial, we explored how to implement push notifications in an Android app using FCM in Java.
Leveraging the powerful features of FCM can enhance communication with users.
Utilize various notification features and real-time data transmission to develop more convenient apps!