Sending Push Notifications Using FCM in Spring Boot

Photo by Heidi Kaden on Unsplash
Photo by Heidi Kaden on Unsplash
Firebase Cloud Messaging (FCM) allows us to send messages to Android, iOS, or web applications, also known as push notifications. This article will introduce how to send push notifications via FCM in Spring Boot.

Firebase Cloud Messaging (FCM) allows us to send messages to Android, iOS, or web applications, also known as push notifications. This article will introduce how to send push notifications via FCM in Spring Boot.

Setup Firebase Console

Go to Firebase Console. If you do not have any Firebase project, please create a new Firebase project first. After that, you must first create an app. If you are not familiar with how to create an app, you can refer to the following article.

Here we create an app named FCM Example.

Firebase Project
Firebase Project

Click the app you created to enter the project settings and switch to Service accounts.

Firebase Service Accounts
Firebase Service Accounts

Click the Generate new private key button, it will pop up the following window. After clicking the Generate key button, you will download a JSON file. After downloading, rename this JSON file to fcm_service_account.json.

Firebase Generate Key
Firebase Generate Key

Creating Spring Boot Server to Send FCM

Importing the Firebase Admin SDK to the Project

First create a new Spring Boot project. Next, you must add the fcm_service_account.json you just downloaded to the project, the path is project/fcm_service_account.json.

Open the project’s build.gradle.kts and add the Firebase Admin SDK.

dependencies {
    ...

    // Firebase cloud message
    implementation("com.google.firebase:firebase-admin:7.1.1")

    ...
}

Initializing FCM

Before sending FCM, we must first initialize the Firebase SDK.

Create FcmInitialization, add @Configuration annotation, and declare a @Bean called initFcm(). initFcm() is an ApplicationRunner, so after the Spring Boot app is initialized, it will be executed first.

initFcm() will read the fcm_service_account.json we added to the project and use it to initialize FirebaseApp.

@Configuration
class FcmInitialization {
    @Bean
    fun initFcm() = ApplicationRunner {
        val fcmCredential = FileInputStream("./fcm_service_account.json")
        val options = FirebaseOptions.builder()
            .setCredentials(GoogleCredentials.fromStream(fcmCredential))
            .build()
        FirebaseApp.initializeApp(options)
    }
}

Sending FCM

Sending to a Single Device

In Spring Boot, you can use Message to create a message to be sent, and use FirebaseMessaging to send it.

val message = Message.builder()
    .setNotification(Notification.builder()
        .setTitle("From Wayne's Talk")
        .setBody("Hello Wayns's Talk")
        .build())
    .putData("payload1", "data1")
    .putData("payload2", "data2")
    .setToken(fcmToken)
    .build()
FirebaseMessaging.getInstance().send(message)

Where fcmToken is the FCM token of the receiving device. Generally speaking, the client app will send the FCM token it receives to the Spring Boot server, and the server will store the FCM token. When a user wants to send FCM, take out the FCM token corresponding to the user, and then use the above code to send FCM.

In addition to the title and text, FCM can also carry key-value data.

Sending to Multiple Devices

FCM also allows you to send to multiple devices at once, just use MulticaseMessage instead. However, a maximum of 500 devices can be sent at a time.

val message = MulticastMessage.builder()
    .setNotification(Notification.builder()
        .setTitle("From Wayne's Talk")
        .setBody("Hello Wayns's Talk")
        .build())
    .putData("payload1", "data1")
    .putData("payload2", "data2")
    .addAllTokens(arrayListOf(fcmToken1, fcmToken2))
    .build()
FirebaseMessaging.getInstance().sendMulticast(message)

Sending to Devices Asynchronously

FirebaseMessaging also provides a corresponding asynchronous sending method. These methods will return a Future.

val future1 = FirebaseMessaging.getInstance().sendAsync(message)
val future2 = FirebaseMessaging.getInstance().sendMulticastAsync(message)

FCM Message Types

There are two types of FCM messages mentioned on the official website , one is Notification message, and the other is Data message.

  • Notification message: FCM will automatically display this message in the notification center of the device, so the user can see the title and content. In addition, this message can also contain key-value data, but it will not be displayed.
  • Data message: This kind of message will only have key-value data, so FCM will not automatically display it in the notification center of the device. Instead, the client app is responsible to process the data in the message itself.

Creating Android App to Receive FCM

You can refer to the following article to build an Android App to receive FCM sent by Spring Boot.

Conclusion

Firebase Cloud Messaging (FCM) provides a front-end and back-end integration package. Allows you to send and receive push notifications. In addition, the received client program also provides multiple platforms, such as Android, iOS, and Web. Next time when you need to use push notifications, FCM is a good choice.

Leave a Reply

Your email address will not be published. Required fields are marked *

You May Also Like