javafirebaseplayframeworkfirebase-cloud-messaging

Firebase device token based push notifications not working in Java Play framework


I am using Java version 8, with Play framework version 2.2.6. My firbase-admin dependency version is 6.8.1.

I tried initializing firebase in my code with the json file provided. Sharing the initialization code for firebase.

/**
 * 
 */
package util.notificationChannel;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;


import com.google.firebase.messaging.FirebaseMessaging;
import com.google.firebase.messaging.Message;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

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


@Service
public class FCMInitializer {

    static Logger LOGGER = LoggerFactory.getLogger(FCMInitializer.class);
    private static final String FIREBASE_CONFIGURATION_PATH = "./kronos-firebase-1182c-firebase-adminsdk.json";

    public static void initialize() {
        try (FileInputStream serviceAccount = new FileInputStream(FIREBASE_CONFIGURATION_PATH)) {
            ByteArrayOutputStream buffer = new ByteArrayOutputStream();
            byte[] temp = new byte[1024];
            int bytesRead;
            while ((bytesRead = serviceAccount.read(temp)) != -1) {
                buffer.write(temp, 0, bytesRead);
            }
            byte[] data = buffer.toByteArray();

            // Use a new ByteArrayInputStream for GoogleCredentials
            ByteArrayInputStream inputStream = new ByteArrayInputStream(data);
            FirebaseOptions options = new FirebaseOptions.Builder()
                    .setCredentials(GoogleCredentials.fromStream(inputStream)).build();

            if (FirebaseApp.getApps().isEmpty()) {
                FirebaseApp.initializeApp(options);
                LOGGER.info("Firebase application has been initialized");
            }
            sendTestNotification();
        } catch (Exception e) {
            LOGGER.error(e.getMessage());
        }
    }

    private static void sendTestNotification() {
        try {
            // Create a test message (for a specific device or topic)
            Message message = Message.builder()
                    .putData("title", "Test")
                    .putData("body", "Firebase connection verified!")
                    .setTopic("test-topic")  // Or use a device token
                    .build();

            // Send the message
            String response = FirebaseMessaging.getInstance().send(message);
            System.out.println("Test notification sent successfully. Response: " + response);
        } catch (Exception e) {
            LOGGER.error("Failed to send test notification: " + e.getMessage(), e);
        }
    }
    
}

I have ensured that the json credentials is getting received. Also I am getting success message like below

Test notification sent successfully. Response: projects/kronos-204907/messages/8849451443820292620

However the app which is connected with the firebase is not receiving the notifications. Any thoughts or suggestions would be really helpful. Thank you


Solution

  • I think you need to create Notification class and pass into Message, just like this :

    private static void sendTestNotification() {
        try {
            // Create a test message (for a specific device or topic)
            Notification notification = Notification.builder()
                    .setTitle("YOUR_TITLE")
                    .setBody("YOUR_BODY/DESCRIPTION")
                    .setImage("YOUR_IMAGE") //This field is optional
                    .build();
    
    
            Message message = Message.builder()
                    .setNotification(notification) //Notification data
                    .setTopic("test-topic")  // Or use a device token
                    .build();
    
            // Send the message
            String response = FirebaseMessaging.getInstance().send(message);
            System.out.println("Test notification sent successfully. Response: " + response);
        } catch (Exception e) {
            LOGGER.error("Failed to send test notification: " + e.getMessage(), e);
        }
    }
    

    I just edit your code,try like this in your java code

    Hope this is work for you.