New Firebase Push Notification By Mighty Springboot: How To

Yow know, Google has announced the deprecation of the FCM XMPP and HTTP legacy APIs. It will be completely removed in June 2024. To stay ahead of these changes, it’s crucial to update your systems in advance. In today’s tutorial, we will explore how to send Firebase Push Notification from a backend server operating on Spring Boot. It will ensure your applications remain efficient and responsive in this new landscape.

Add Firebase Admin SDK:

Add below code to install admin sdk in your Spring Boot Project:

<dependency>
    <groupId>com.google.firebase</groupId>
    <artifactId>firebase-admin</artifactId>
    <version>8.0.0</version>
</dependency>

Download Configuration File

To initialize your admin SDK you have to download your Firebase project’s configuration file. Go to your firebase console and open your project. Click on gear icon.

Firebase Push Notification

Select Project settings and go to Service Account:

Firebase Push Notification

Click on Generate new provate key. It will download the configuration json file.

Initializing Firebase Admin SDK

You have to simply copy that configuration json file and paste it into resources folder of your Spring Boot project. See the example picture below:

Firebase Push Notification

Create a class and name it Constants.java. Create a method and name it initFirebase()

import com.google.auth.oauth2.GoogleCredentials;
import com.google.firebase.FirebaseApp;
import com.google.firebase.FirebaseOptions;

import java.io.InputStream;

public class Constants {
    
    public static final String FIREBASE_PROJECT_NAME = "your project name";

    public void initFirebase() throws Exception {

        InputStream projectKey = Constants.class.getResourceAsStream("/your-project-configuration.json");
        
        FirebaseOptions projectOption = FirebaseOptions.builder()
                .setCredentials(GoogleCredentials.fromStream(projectKey))
                .build();
        

        if(FirebaseApp.getApps().size() == 0){
            FirebaseApp.initializeApp(projectOption, FIREBASE_PROJECT_NAME);
        }

    }
}

After that use this Constant class in your Spring Boot project start up:

import com.captaindroid.Ludo.utils.Constants;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import java.io.IOException;

@SpringBootApplication
public class MyApplication {

	public static void main(String[] args) throws InterruptedException, IOException {

		SpringApplication.run(MyApplication.class, args);

		try {
			new Constants().initFirebase();
		} catch (Exception e) {}

	}

}

And thus you are done with initializing.

Send Firebase Push Notification

Continuing further. How do you finally send notification? It’s simple. You can send the notification when you receive a http request or you can schedule it in your Spring Boot application to send Firebase push notification. To any topic or specific user’s device. We will see both example.

Firebase Push Notification using http request:

Hence it’s http request, we will use http GET method in this example. Just to keep it simple. You can also use POST, PUT, DELETE etc:

import com.captaindroid.Ludo.component.SpringContext;
import com.captaindroid.Ludo.model.User;
import com.captaindroid.Ludo.repos.UserRepository;
import com.captaindroid.Ludo.utils.Constants1;
import com.google.firebase.FirebaseApp;
import com.google.firebase.messaging.FirebaseMessaging;
import com.google.firebase.messaging.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;


@Controller
public class UserController {

    @Autowired
    public UserRepository userRepository;

    @ResponseBody
    @GetMapping(value = "/notifyUser")
    private ResponseEntity<Object> notifyUsers(@RequestParam("email") String email) {

        if (email == null) {
            return new ResponseEntity<>("Email not provided", HttpStatus.BAD_REQUEST);
        }

        User user = userRepository.findByEmail(email);

        if (user != null) {
            try {
                Message message = Message.builder()
                        .putData("body", "your data")
                        .putData("title", "Congratulation " + user.getFirstName() + ", you won ....")
                        .putData("phoneId", user.getPhoneNumber + "")
                        .putData("image_url", user.getProfileImage())
                        .setToken(user.getDeviceToken)
                        .build();
                FirebaseMessaging.getInstance(FirebaseApp.getInstance(Constants.FIREBASE_PROJECT_NAME)).send(message);
            } catch (Exception e) {

            }
        } else {
            return new ResponseEntity<>("User not found", HttpStatus.NOT_FOUND);
        }
        return new ResponseEntity<>("Notification sent successfully", HttpStatus.OK);
    }

}

Firebase Push Notification using @Scheduled

Afterwards, let’s see how we can use Spring Boot’s @Scheduled to send Firebase Push Notification. in UserController class create a method and name it sendNotification(). In this method we will send notification using topic:

...
...

@Controller
public class UserController {

    ...
    ...

    @Scheduled(fixedDelay = 28800000) // every 8 Hours
    public void sendNotification() {
        if (!SpringContext.getEnvironment().getProperty("isProd", Boolean.class)) {
            return;
        }

        try {
            Message message = Message.builder()
                    .putData("body", "your data")
                    .putData("title", "New topic example")
                    .putData("image", "your image url")
                    .setTopic("your_topic")
                    .build();
            FirebaseMessaging.getInstance(FirebaseApp.getInstance(Constants1.FIREBASE_PROJECT_NAME)).send(message);
        } catch (Exception e) {

        }
    }


Here, fixedDelay = 28800000 means this method will be called every 8 hours.

Conclusion


In conclusion, the integration of Firebase Push Notifications with a Spring Boot backend server marks a significant advancement for developers looking to enhance their application’s communication capabilities. Through the steps outlined in this blog, from setting up Firebase in your Spring Boot project to crafting and sending notifications, it’s clear that this approach not only streamlines the notification process but also opens up new avenues for engaging users more effectively.

As we’ve navigated through the intricacies of sending Firebase Push Notifications, the potential for creating more interactive and responsive applications has come to light. This method stands out not just for its efficiency and reliability but also for its adaptability across various platforms and devices.

With Google phasing out the FCM XMPP and HTTP legacy APIs by June 2024, the shift to utilizing the Firebase Push Notification with Spring Boot becomes not just an option but a necessity for staying ahead. This guide aims to prepare you for this transition, ensuring that your applications continue to deliver exceptional user experiences without interruption.