Home » Push Notification » How to configure Firebase Java SDK

How to configure Firebase Java SDK

Here I have used the spring project to configure firebase java SDK. For integrating java SDK let me explain what we have to do in Firebase Console and Spring Project.

  1. Download Admin SDK configuration snippet from Firebase Console.
  2. Integrate Admin SDK with Spring Project

Download Admin SDK Configuration snippet from Firebase.

Firebase provides the java SDK snippet as a JSON file. We have to download it and configure it in the Spring project.

  1. How to download Admin SDK Snippet Json File

First, select the project which you want to use from the firebase console then go to the project overview section and click the setting icon. In the settings option, you can see lots of options general, cloud messaging, service accounts and etc...In that please choose the service account option.

Firebase provides Admin SDK Configuration JSON in many platforms like java, Nodes.js, Python and etc. Here we are going to use java SDK so please choose java then click Generate new private key button to download the JSON file. That’s it. Then keep this file in the resources folder in the spring project and use it.

firebase java sdk

Integrate Admin SDK with Spring Project

Please include the maven dependency in pom.xml file.

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

The below snippet is used to initialize the firebase app. We have to initialize the app before pushing the notifications.

FileInputStream serviceAccount = new FileInputStream(ResourceUtils.getFile("classpath:config/serviceAccountKey.json"));
try {
    FirebaseOptions options = new FirebaseOptions.Builder()
        .setCredentials(GoogleCredentials.fromStream(serviceAccount))
        .setDatabaseUrl("https://sample-86c33.firebaseio.com")
        .build();
    if (FirebaseApp.getApps().isEmpty()) {
        FirebaseApp.initializeApp(options);
    }
} catch (Exception e) {
    System.out.println(e.getMessage());
} finally {
    serviceAccount.close();
}

We have to give the right location where we kept the admin SDK JSON file. Please replace this "path/to/serviceAccountKey.json" with the right location of your JSON file.

The below snippet is an example of sending a push notification (or) multicast message to the list of device tokens. If you don’t know about device tokens then please go to this link (Sending Push Notification).

//add your device token here
List < String > tokenList = new ArrayList < String > ();
MulticastMessage message = message = MulticastMessage.builder()
    .putData("title", "Hi")
    .putData("description", "Hi Dude, How are you?")
    .putData("imageUrl", "sampleimageurl")
    .setNotification(new Notification("Hi", "Hi Dude How are you?", "sampleimageurl"))
    .addAllTokens(tokenList)
    .build();
//Sending Push Notification
BatchResponse response = FirebaseMessaging.getInstance().sendMulticast(message);
System.out.println(response);

In the above snippet, you can see putData and setNotification methods. The data which we set for this method will be passed as data JSON and notification JSON to mobile devices.

Data JSON is the custom one, we can put n number of data. But notification JSON we can only set title, body, and image. Simply say notification messages are called display messages this will be handled by firebase java SDK.

Data messages are custom one which will be handled by android or ios or web app. The above example is for sending a multicast message from Firebase Cloud Messaging.

Firebase Cloud Messaging from Admin SDK

There are many methods available in FCM to send different types of messages to the client app.

Method NamePurpose
sendsends a single message
sendAllsends the array of messages
sendMulticastsends the multicast message to all the registered tokens
sendToConditionsends FCM message to a particular condition
sendToDevicesends a message to a single device with the corresponding registered token
sendToDeviceGroupsends a message to a group of devices
sendToTopicsends the message to a particular topic
subscribeToTopicsends the message to devices that subscribed under a topic
unsubscribeFromTopicunsubscribe a device from a topic

The above table lists all the methods of sending different types of messages from Firebase Cloud Messaging. Here I explained the method with a purpose of use briefly. If you want to know in-depth of the functionalities then please take a look at Firebase Messaging.

The below snippet is for your reference that contains all the examples of all the methods.

FirebaseMessagingSnippets.java

package com.google.firebase.example;
import com.google.firebase.messaging.AndroidConfig;
import com.google.firebase.messaging.AndroidNotification;
import com.google.firebase.messaging.ApnsConfig;
import com.google.firebase.messaging.Aps;
import com.google.firebase.messaging.ApsAlert;
import com.google.firebase.messaging.FirebaseMessaging;
import com.google.firebase.messaging.Message;
import com.google.firebase.messaging.Notification;
import com.google.firebase.messaging.TopicManagementResponse;
import com.google.firebase.messaging.WebpushConfig;
import com.google.firebase.messaging.WebpushNotification;
import java.util.Arrays;
import java.util.List;

public class FirebaseMessagingSnippets {

    public void sendToToken() throws Exception {
        // [START send_to_token]
        // This registration token comes from the client FCM SDKs.
        String registrationToken = "YOUR_REGISTRATION_TOKEN";

        // See documentation on defining a message payload.
        Message message = Message.builder()
            .putData("score", "850")
            .putData("time", "2:45")
            .setToken(registrationToken)
            .build();

        // Send a message to the device corresponding to the provided
        // registration token.
        String response = FirebaseMessaging.getInstance().sendAsync(message).get();
        // Response is a message ID string.
        System.out.println("Successfully sent message: " + response);
        // [END send_to_token]
    }

    public void sendToTopic() throws Exception {
        // [START send_to_topic]
        // The topic name can be optionally prefixed with "/topics/".
        String topic = "highScores";

        // See documentation on defining a message payload.
        Message message = Message.builder()
            .putData("score", "850")
            .putData("time", "2:45")
            .setTopic(topic)
            .build();

        // Send a message to the devices subscribed to the provided topic.
        String response = FirebaseMessaging.getInstance().sendAsync(message).get();
        // Response is a message ID string.
        System.out.println("Successfully sent message: " + response);
        // [END send_to_topic]
    }

    public void sendToCondition() throws Exception {
        // [START send_to_condition]
        // Define a condition which will send to devices which are subscribed
        // to either the Google stock or the tech industry topics.
        String condition = "'stock-GOOG' in topics || 'industry-tech' in topics";

        // See documentation on defining a message payload.
        Message message = Message.builder()
            .setNotification(new Notification(
                "$GOOG up 1.43% on the day",
                "$GOOG gained 11.80 points to close at 835.67, up 1.43% on the day."))
            .setCondition(condition)
            .build();

        // Send a message to devices subscribed to the combination of topics
        // specified by the provided condition.
        String response = FirebaseMessaging.getInstance().sendAsync(message).get();
        // Response is a message ID string.
        System.out.println("Successfully sent message: " + response);
        // [END send_to_condition]
    }

    public void sendDryRun() throws Exception {
        Message message = Message.builder()
            .putData("score", "850")
            .putData("time", "2:45")
            .setToken("token")
            .build();

        // [START send_dry_run]
        // Send a message in the dry run mode.
        boolean dryRun = true;
        String response = FirebaseMessaging.getInstance().sendAsync(message, dryRun).get();
        // Response is a message ID string.
        System.out.println("Dry run successful: " + response);
        // [END send_dry_run]
    }

    public Message androidMessage() {
        // [START android_message]
        Message message = Message.builder()
            .setAndroidConfig(AndroidConfig.builder()
                .setTtl(3600 * 1000) // 1 hour in milliseconds
                .setPriority(AndroidConfig.Priority.NORMAL)
                .setNotification(AndroidNotification.builder()
                    .setTitle("$GOOG up 1.43% on the day")
                    .setBody("$GOOG gained 11.80 points to close at 835.67, up 1.43% on the day.")
                    .setIcon("stock_ticker_update")
                    .setColor("#f45342")
                    .build())
                .build())
            .setTopic("industry-tech")
            .build();
        // [END android_message]
        return message;
    }

    public Message apnsMessage() {
        // [START apns_message]
        Message message = Message.builder()
            .setApnsConfig(ApnsConfig.builder()
                .putHeader("apns-priority", "10")
                .setAps(Aps.builder()
                    .setAlert(ApsAlert.builder()
                        .setTitle("$GOOG up 1.43% on the day")
                        .setBody("$GOOG gained 11.80 points to close at 835.67, up 1.43% on the day.")
                        .build())
                    .setBadge(42)
                    .build())
                .build())
            .setTopic("industry-tech")
            .build();
        // [END apns_message]
        return message;
    }

    public Message webpushMessage() {
        // [START webpush_message]
        Message message = Message.builder()
            .setWebpushConfig(WebpushConfig.builder()
                .setNotification(new WebpushNotification(
                    "$GOOG up 1.43% on the day",
                    "$GOOG gained 11.80 points to close at 835.67, up 1.43% on the day.",
                    "https://my-server/icon.png"))
                .build())
            .setTopic("industry-tech")
            .build();
        // [END webpush_message]
        return message;
    }

    public Message allPlatformsMessage() {
        // [START multi_platforms_message]
        Message message = Message.builder()
            .setNotification(new Notification(
                "$GOOG up 1.43% on the day",
                "$GOOG gained 11.80 points to close at 835.67, up 1.43% on the day."))
            .setAndroidConfig(AndroidConfig.builder()
                .setTtl(3600 * 1000)
                .setNotification(AndroidNotification.builder()
                    .setIcon("stock_ticker_update")
                    .setColor("#f45342")
                    .build())
                .build())
            .setApnsConfig(ApnsConfig.builder()
                .setAps(Aps.builder()
                    .setBadge(42)
                    .build())
                .build())
            .setTopic("industry-tech")
            .build();
        // [END multi_platforms_message]
        return message;
    }

    public void subscribeToTopic() throws Exception {
        String topic = "highScores";
        // [START subscribe]
        // These registration tokens come from the client FCM SDKs.
        List < String > registrationTokens = Arrays.asList(
            "YOUR_REGISTRATION_TOKEN_1",
            // ...
            "YOUR_REGISTRATION_TOKEN_n"
        );

        // Subscribe the devices corresponding to the registration tokens to the
        // topic.
        TopicManagementResponse response = FirebaseMessaging.getInstance().subscribeToTopicAsync(
            registrationTokens, topic).get();
        // See the TopicManagementResponse reference documentation
        // for the contents of response.
        System.out.println(response.getSuccessCount() + " tokens were subscribed successfully");
        // [END subscribe]
    }

    public void unsubscribeFromTopic() throws Exception {
        String topic = "highScores";
        // [START unsubscribe]
        // These registration tokens come from the client FCM SDKs.
        List < String > registrationTokens = Arrays.asList(
            "YOUR_REGISTRATION_TOKEN_1",
            // ...
            "YOUR_REGISTRATION_TOKEN_n"
        );

        // Unsubscribe the devices corresponding to the registration tokens from
        // the topic.
        TopicManagementResponse response = FirebaseMessaging.getInstance().unsubscribeFromTopicAsync(
            registrationTokens, topic).get();
        // See the TopicManagementResponse reference documentation
        // for the contents of response.
        System.out.println(response.getSuccessCount() + " tokens were unsubscribed successfully");
        // [END unsubscribe]
    }
}

Hope you will be getting a great idea of integrating Firebase Java SDK and Firebase Cloud Messaging. If you want to know more about Firebase Cloud Messaging please go through this official Documentation from Firebase.

Leave a Reply

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