If you need to send localised push notifications from a Java server side application to mobile devices with Firebase Cloud Messaging (FCM), whether your server side is Grails, Spring boot or any other Java based framework utilising the Firebase (Admin) SDK then search no more as it's not so clear in the official documentation. Most examples focus on the REST or JS implementations.
In my use case, I wanted to alert users subscribing to a specific Topic of a particular event. Users of this app are distributed globally so it was important to localise the messages depending on the users locale according to their device. From the server side, I just want to generate the notification and let Firebase's servers handle the notifications to each device subscribed to the topic and then the device it self display a locales message, both the title and subtitle, on both Android and IOS devices.
Fortunately Firebase lets us do this by specifying localised 'keys', instead of specifying the title and body. However finding an example was more of a struggle as the documentation is somewhat lacking.
What we have to do is establish Options objects for each platform, i.e. one for Android and one for Apple devices and then deep within nested Builders we can finally set the localised keys. These then can be interpreted from the resources within the mobile App itself and will be displayed to the user, both when the app is in the foreground AND also when it's in the background.
So without further ado, let's look at the code:
Note: I'm omitting the rest of the app code assuming you already know how to setup Firebase etc and just need to see how to generate the notification.
void sendLocalisedNotification(String topic, String titleKey, String bodyKey) {
// Set localisation key for Android
AndroidConfig androidConfig = AndroidConfig.builder()
.setNotification(
AndroidNotification.builder()
.setTitleLocalizationKey(titleKey)
.setBodyLocalizationKey(bodyKey)
.build()
).build()
// Set localisation key for Apple devices
ApnsConfig apnsConfig = ApnsConfig.builder()
.setAps(Aps.builder()
.setAlert(ApsAlert.builder()
.setTitleLocalizationKey(titleKey)
.setSubtitleLocalizationKey(bodyKey)
.build()
).build()
).build()
Message message = Message.builder()
.setTopic(topic)
.setAndroidConfig(androidConfig)
.setApnsConfig(apnsConfig)
.build();
// And then send the message to the devices subscribed to the provided topic.
try {
String response = FirebaseMessaging.getInstance().send(message);
// Response is a message ID string.
log.debug("Firebase message $topic sent: " + response);
} catch (Exception ex) {
log.warn("Firebase message $topic failed: " + ex.message);
}
}
So that's the gist of it, this method can be called with the topic we want to publish to, the title key and the body key.
I hope this helps save someone time discovering how to accomplish localised messages under a Java environment using the FCM SDK.
Dave / Tucanoo Solutions
Top comments (0)