Android FCM — Sharing is caring!

.
6 min readAug 14, 2018
FCM in a nutshell. (Animation made by The Firebase Blog by Google)

FCM or Firebase Cloud Messaging, what‘s the rush?

1. Polling vs. Pushing
Chats and social media apps share one thing in common — they all connect to the internet and receive their data from a server.

For app to work like that we need a client app and a web server. Engineers who work on servers knows as back-end engineers.

As client side engineers we need to decide how to sync data to our app with the data on the server. There are two data syncing strategies:

(a) Polling — The act of continually pinging the server every so often to see if there are any updates. Apps using JobSchedulers or sync adapters using the polling strategy. We need to be careful to not uselessly pinging the server, otherwise it will drain the battery.

Using the wireless radio is one of the most battery-draining things we can do on an Android device. Every time the wireless radio is used, our device needs to power up the radio, which is especially costly. It is much better to do a bunch of network activity all at once.

(b) Pushing — Apps that need data in real time used that strategy. In pushing strategy the server is responsible for telling the phone when it has new information. It is mostly used when we talk to a server that gets updates not in a regular time. The server can decide what information to send down in the message. Once the client app received the message it’s up to the client app how to respond.

Pushing as an update strategy is always more battery efficient than polling.
The cost is that we need to change the code both in the app and in the server.

2. Intro to Firebase Cloud Messaging
Pushing is a good strategy when we are looking to have real time updates and spare our users battery.

How can we set up pushing strategy?
Server side:
- Our server to keep track of the different client devices
- Our server needs to be able to deliver messages, even if one of the phones temporarily loses connectivity, or is off.

Client side:
- Our app needs to be configured to handle messages from the server

Google simplifies pushing by offering a cloud messaging service called Firebase Cloud Messaging, or FCM for short. FCM service has 2 parts:

(a) FCM server — Manages and sends messages to our client devices.
(b) Android client FCM messaging library — Allows you to receive messages from the FCM server on the client app.

FCM gives you some free functionality:

(a) Automatic retries — FCM will know when the message has been sent successfully.
(b) Mass messages — Send messages to groups of phones and multiple devices.
(c) Cross platform — Work for Android, iOS and the web.
(d) Scale — FCM could deliver messages to huge numbers of users fast.

3. Intro to Firebase
In May 2016, Google took a pre-existing product called Firebase and expanded it into what is now a one stop shop for a bunch of technologies that make building mobile and web apps easier.

Firebase is a platform where you can mix and match common features of web and mobile apps, and then use Google SDKs to include them in your app. A lot of google services were packed as part of Firebase.

How to set up FCM?

(a) Make a Firebase account
(b) Make a new Firebase project
(c) Configure the project with the Android client
(d) Send your first message

Every separate project that you have that uses Firebase should have a different Firebase project associated with it. A single project may have multiple types of app platforms (clients) associated with it. Connecting to Firebase will involve some configuration in the Firebase console, along with changing a few things in your Android app to add the Firebase SDK.

4. Intro to messages
The firebase console sends message to the FCM server that will be sent to our app (client).

The way the notification data is bundled looks like a json, with the “notification” as the main object and “body” as the message itself. Using the Firebase console its possible to send extra data in the form of key-value pairs.

The automatically generated notification on your device will open the activity using an intent, which have our extra data that we’ve sent along with the message.

By using the extra data we can detect weather the intent that opened the app came from FCM or not. So, we can make our app react differently if it was launched from the FCM notification as opposed to somewhere else.

The ability to accept a ping from FCM and then turn it into a notification which then opens up your app is a feature that’s built in to the FCM SDK.

We can target everybody uses the app using “user segment” or a single device using FCM registration token, which uniquely identify a device. It’s generated when the app first starts and changes when we reinstall the app. We can find it by printing it to the log while creating a service that would extends from FirebaseInstanceIdService.

We can send real data messages, not just notifications, by creating our own server that can talk to the FCM server to send out the messages.

There is a difference between notification messages and data messages.
Our app will react differently when it gets a notification message or data message.

Notification message:
- Main json object is “notification”
- Display notification automatically when the app is in the background
- Predefined key values (“body”)
- Extra values in intent extra
- Can be sent from Firebase console
- App in the background: shows notification
- App in the foreground: triggers onMessageReceived()
* Example: advertisements or notifications

Data message:
- Main json object is “data”
- Requires you to do all the data processing
- All custom key value pairs
- Cannot be sent from Firebase console
- App in foreground or background triggers onMessageReceived()
* Example: Email app that should sync

Notification and data message combined:
- Cannot be sent from the Firebase console
- Behave like a notification message
- App in the background: shows notification, does not trigger onMessageReceived(), the notification has extras in the intent
- App in the foreground: triggers onMessageReceived()

To receive and process a data message, you need to implement another service called FirebaseMessagingService. We can do it by implementing the next steps:

(a) Create service that extends FirebaseMessagingService
(b) Add service to manifest with MESSAGING_EVENT intent filter
(c) Override onMessageReceived()

This will create a service on your client phone that is triggered by incoming FCM data messages, as well as notification messages when the app is in the foreground. This is useful because it means the app can be in the background and get pinged by FCM data message. We can execute any code we want in onMessageReceived().

The onMessageReceived() takes a RemoteMessage object as a parameter. You can use this object to get a map of the data contained within the message by calling getData(). getData() will return a map object with keys and values that are both strings.

In conclusion, whether the incoming message is a data message or a notification message is determined bb whoever built the server. We have the choice.

5. Sending to multiple devices
To get global reach we want to send updates to many followers. There are a few ways to send data to multiple phones using FCM:

(a) Device groups — Typically sets of devices that all belong to the same user (ex: 2 phones and a tablet with the same app). We can store sets of devices together in a device group. The creation and management of these device groups is done all in the server side on the app server.

(b) Topics — Topics are like mailing lists. Some client devices will choose to subscribe to a topic, and then only those devices which subscribed will be sent the messages when the topic sends a message.

How topics look like in code?

On the server side, instead of sending a message to a specific id, we could send the message to a topic. A topic is represented by a single string key. Note that the topic key will always come after the word “topics”, surrounded by forward slashes. Client devices can subscribe and unsubscribe to topics using that key.

This would then send the associated data or notification message to all client devices that are registered to that topic. The key we subscribe to and the key the server sends the message to — must be identical.

REFERENCES:

You can find much more at the free course Advanced Android App Development by Google on the Udacity website over here: (check it out!)

https://classroom.udacity.com/courses/ud855

--

--