Send firebase push notifications From Spring Boot.

Author : usitvhd
Publish Date : 2021-04-08 17:49:38


 

Let’s learn how to send push notifications to iOS and android mobile devices via firebase cloud messaging(FCM) service using Spring Boot with an example.

Mobile notifications play a major role in user engagement. With the firebase’s new SDK for java, sending Firebase push notification from a Spring Boot application got a lot easier.

Usually, FCM notifications were done via a rest call to https://fcm.googleapis.com/fcm/send with a JSON request. Even though this method seems simple to connect to Firebase Cloud Messaging also known as FCM, once you span across iOS and web-push, things can get out of hand pretty soon. For this reason, Firebase SDK comes with predefined methods that can help clear this mess.
Table of contents

    1) Setup Firebase messaging dependency
    2) Get Service Account Private Key from FCM Console
    3) Configure Spring Bean for Push notification
    4) Write a Push notification Service
        4.1) Understand how Firebase Library works
    5) Write a Test Controller
    6) Verifying push notification from Spring Boot
    7) Summary & Sample Code

1) Setup Firebase messaging dependency

To include the Firebase-SDK you need to add the following maven dependency to your project.

<dependency>
     <groupId>com.google.firebase</groupId>
     <artifactId>firebase-admin</artifactId>
     <version>7.0.0</version>
</dependency>
Code language: HTML, XML (xml)

2) Get Service Account Private Key from FCM Console

The next thing you have to do is to generate a service-account.json. For this open the Service Accounts in FCM console and click Generate Private Key.

Screen to download firebase admin private key for sending notifications

This will download a file in the form of <firebase-project>-firebase-adminsdk-<hash>.json. Save this file src/java/resources as firebase-service-account.json.
3) Configure Spring Bean for Push notification

In our spring boot application, Let’s create an object for FirebaseMessaging and register it as a bean. This bean will be used to send notifications.

https://thegdwheel.com/advert/frozen-four-minnesota-state-vs-st-cloud-state-live-stream-college-hockey-semifinal-free/

https://thegdwheel.com/advert/hockey-semifinal-st-cloud-state-vs-minnesota-state-live-stream-college-hockey-semifinal-free/

https://thegdwheel.com/advert/frozen-four-game-minnesota-duluth-vs-massachusetts-live-stream-college-hockey-semifinal-free/

https://thegdwheel.com/advert/hockey-semifinal-massachusetts-vs-minnesota-duluth-live-stream-college-hockey-semifinal-free/

https://thegdwheel.com/advert/watch-free-umass-vs-minnesota-duluth-live-stream-college-hockey-semifinal-free/


https://thegdwheel.com/advert/live-free-hockey-frozen-four-semifinal-2021-live-stream-ncaa-college-hockey-free/


https://thegdwheel.com/advert/123movieswatch-godzilla-vs-kong-2021-full-movie-online-download-for-free/

https://thegdwheel.com/advert/hbomax2021godzilla-vs-kong-watch-full-film-online-free-en-linea-full-hd-gratis/

https://blog.goo.ne.jp/linkup/e/e6194e268495a08be133f6adb61f41ad

https://www.deviantart.com/fgdffdfd/journal/Send-firebase-push-notifications-From-875744714

https://paiza.io/projects/O7EdtwpQ7BX3zmhsGQxnkQ

https://caribbeanfever.com/photo/albums/send-firebase-push

@Bean
FirebaseMessaging firebaseMessaging() throws IOException {
    GoogleCredentials googleCredentials = GoogleCredentials
            .fromStream(new ClassPathResource("firebase-service-account.json").getInputStream());
    FirebaseOptions firebaseOptions = FirebaseOptions
            .builder()
            .setCredentials(googleCredentials)
            .build();
    FirebaseApp app = FirebaseApp.initializeApp(firebaseOptions, "my-app");
    return FirebaseMessaging.getInstance(app);
}
Code language: Java (java)

Here new ClassPathResource("firebase-service-account.json").getInputStream() is an easier way to create an InputStream for a file that is in classpath. With this we created a FirebaseApp object from which we got our FirebaseMessaging instance.
4) Write a Push notification Service

I wrote a simple FirebaseMessagingService by using the bean that we just created. In a very basic use case, the class would look like this.

@Service
public class FirebaseMessagingService {

    private final FirebaseMessaging firebaseMessaging;

    public FirebaseMessagingService(FirebaseMessaging firebaseMessaging) {
        this.firebaseMessaging = firebaseMessaging;
    }


    public String sendNotification(Note note, String token) throws FirebaseMessagingException {

        Notification notification = Notification
                .builder()
                .setTitle(note.getSubject())
                .setBody(note.getContent())
                .build();

        Message message = Message
                .builder()
                .setToken(token)
                .setNotification(notification)
                .putAllData(note.getData())
                .build();

        return firebaseMessaging.send(message);
    }

}
Code language: Java (java)

4.1) Understand how Firebase Library works

Here, The Notification object captures what Title and Body to show on the mobile notification.

The Message object has multiple builder methods to deal with various scenarios.

    Send a message to a specific recipient by using setToken(String) or you can send it to anyone who is subscribed to a topic by using setTopic(String)
    Pass additional data to the mobile applications using putData(String, String) or putAllData(Map<String, String>).
    Customize options specific to Android, iOS and web clients using the below builder methods respectively.
        setAndroidConfig()
        setApnsConfig()
        setWebpushConfig()
    Each of these methods have a set of builder methods to back their confuguration further.

Once you have created a message object with appropriate values, then you can call firebaseMessaging.send(Message) to submit the request. The method will return a String which represents the message ID that was sent during the API call. There is no need to store this value. Note that there can be a FirebaseMessagingException if there is an error while processing the message while sending. So make sure you handle it.
5) Write a Test Controller

Let’s write a simple test API call.

@Data
public class Note {
    private String subject;
    private String content;
    private Map<String, String> data;
    private String image;
}

/*******************************/

@RequestMapping("/send-notification")
@ResponseBody
public String sendNotification(@RequestBody Note note,
                               @RequestParam String token) throws FirebaseMessagingException {
    return firebaseService.sendNotification(note, token);
}
Code language: Java (java)

6) Verifying push notification from Spring Boot

A simple curl command with a sample post date yields the following result.

$ curl -X POST "http://localhost:8080/send-notification?topic=gold"
  -H "Content-Type: application/json"
  -d '{
    "subject": "some subject",
    "content": "Some long content",
    "image": "https://somedomain.com/example.jpg",
    "data": {
      "key1": "Value 1",
      "key2": "Value 2",
      "key3": "Value 3",
      "key4": "Value 4"
    }
  }'

HTTP/1.1 200
Content-Type: text/plain;charset=UTF-8
Content-Length: 53
Date: Thu, 10 Sep 2020 14:21:50 GMT
Keep-Alive: timeout=60
Connection: keep-alive

projects/spring-demo/messages/2282285117414704507
Code language: Bash (bash)

spring boot firebase mobile notification example screenshotA sample mobile push notification from Spring Boot

Notice how the response is projects/spring-demo/messages/2282285117414704507 which is the message ID of the fired message to FCM. We can use this message ID to debug the business logic on the client side.

    Note that in the GitHub example, You will have to replace the firebase-service-account.json downloaded from your FCM project.

7) Summary & Sample Code

We learned how to send firebase cloud messaging push notifications using Spring Boot with an example.

You can play with the demo project here in this github repository. Also, If you liked this article, please checkout the following write-ups.

    Send HTML emails with FreeMarker Templates – Spring Boot
    Thymeleaf Expressions in Spring Boot
    Spring Boot Email using Thymeleaf with Example
    Spring Boot RabbitMQ – Complete Guide For Beginners
    Install and Run Spring Boot Linux Service Guide

 



Catagory :general