Wednesday, July 3, 2024
HomeLanguagesJavaHow to Use Firebase Cloud Messaging (FCM) in Android?

How to Use Firebase Cloud Messaging (FCM) in Android?

Firebase Cloud Messaging (FCM) is a service provided by Google that allows developers to send push notifications to Android, iOS, and web devices. FCM uses Google Cloud Messaging (GCM) as the underlying technology for sending and receiving messages but offers additional features such as the ability to send messages to specific groups of devices and to receive notifications when a message has been sent. FCM also includes support for sending messages to devices that are offline, and for sending messages with custom data payloads. To use FCM in an Android app, you will need to set up a Firebase project in the Firebase console, and then integrate the FCM SDK into your app.

Step-By-Step Approach to using FCM in an Android App

Step 1: Create a new Firebase project in the Firebase console

 

Step 2:  In the Firebase console, navigate to the “Cloud Messaging” tab and copy the “Server key” and “Sender ID”.

Step 3: In your Android app, add the Firebase Cloud Messaging (FCM) library to your app-level build.gradle file:

implementation 'com.google.firebase:firebase-messaging:20.2.4'

Step 4: In the AndroidManifest.xml file, add the following permissions:

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WAKE_LOCK" />

Step 5: Create a new class that extends FirebaseMessagingService and overrides the onMessageReceived method. This is where you will handle incoming messages.

Step 6: In this class, call the method FirebaseInstanceId.getInstance().getToken() to retrieve the FCM token for the device.

Step 7: Create a new instance of the RemoteMessage.Builder class, and use it to construct the message you want to send. You can set the message’s destination, data payload, and notification options using the builder’s methods.

Step 8: Use the FirebaseMessaging.getInstance().send() method to send the message to the specified device.

Step 9: On the client side, use the FCM SDK to register for push notifications and handle them when they arrive.

Step 10: You can also use Firebase Cloud Functions to send messages, this way you don’t need to store the FCM token in your database, instead, you can use Firebase Authentication to send messages to specific users. This is a general overview of the process, and it may vary depending on your specific use case. Keep in mind that FCM is a powerful tool, but it requires proper setup and configuration to work correctly.

Code Snippet for FCM to send a notification to an Android device in Java and Kotlin

Java




import com.google.firebase.messaging.FirebaseMessaging;
import com.google.firebase.messaging.RemoteMessage;
  
public class FCMExample {
    public static void main(String[] args) {
        FirebaseMessaging fcm = FirebaseMessaging.getInstance();
  
        // Build the message to be sent
        RemoteMessage message = new RemoteMessage.Builder("your_sender_id")
                .setMessageId("unique_message_id")
                .addData("title", "Hello World!")
                .addData("body", "This is a test notification.")
                .build();
  
        // Send the message
        fcm.send(message);
    }
}


Kotlin




import com.google.firebase.messaging.FirebaseMessaging
import com.google.firebase.messaging.RemoteMessage
  
fun main() {
    val fcm = FirebaseMessaging.getInstance()
  
    // Build the message to be sent
    val message = RemoteMessage.Builder("your_sender_id")
            .setMessageId("unique_message_id")
            .addData("title", "Hello World!")
            .addData("body", "This is a test notification.")
            .build()
  
    // Send the message
    fcm.send(message)
}


For a complete example project please refer to this article: How to Push Notification in Android using Firebase Cloud Messaging

Nokonwaba Nkukhwana
Experience as a skilled Java developer and proven expertise in using tools and technical developments to drive improvements throughout a entire software development life cycle. I have extensive industry and full life cycle experience in a java based environment, along with exceptional analytical, design and problem solving capabilities combined with excellent communication skills and ability to work alongside teams to define and refine new functionality. Currently working in springboot projects(microservices). Considering the fact that change is good, I am always keen to new challenges and growth to sharpen my skills.
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments