DEV Community

Nguyễn Hữu Hiếu
Nguyễn Hữu Hiếu

Posted on

1

react native firebase fcm (firebase messaging cloud) + java spring boot: how to push notification

How to push FCM Notification with Java

Scenarior

  • Just use for data-only message
  • Need an extra field to contain id of notification
  • If use notification like normal => not have id
  • Want to custom notification
  • Send notification for quit + foreground + background
@Slf4j
@SpringBootTest
public class FcmTests {

    @Autowired
    FirebaseMessaging firebaseMessaging;

    @Test
    public void test1() throws FirebaseMessagingException {
        log.info("FCM Sending...");

        List<String> registrationTokens = Collections.singletonList("<your fcm token here>");

        // iOS Config
        Aps aps = Aps.builder()
                .setContentAvailable(true)
                .build();
        ApnsConfig apnsConfig = ApnsConfig.builder()
                .setAps(aps)
                .build();
        // android config
        AndroidConfig androidConfig = AndroidConfig.builder()
                .setPriority(AndroidConfig.Priority.HIGH)
                .build();

        MulticastMessage message = MulticastMessage.builder()
                .putData("title", "you can do everything")
                .putData("id", "1")
                .putData("body", "jumppp....")
                .setAndroidConfig(androidConfig)
                .setApnsConfig(apnsConfig)
                .addAllTokens(registrationTokens)
                .build();
        BatchResponse response = firebaseMessaging.sendMulticast(message);
        // See the BatchResponse reference documentation
        // for the contents of response.
        log.info("FCM Send success count=[{}]", response.getSuccessCount());
    }
}

Enter fullscreen mode Exit fullscreen mode

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay