Firebase Cloud Messaging (FCM) is the new version of GCM. It inherits the reliable and scalable GCM infrastructure, plus new features! See the FAQ to learn more. If you are integrating messaging in a new app, start with FCM. GCM users are strongly recommended to upgrade to FCM, in order to benefit from new FCM features today and in the future.

Messaging Concepts and Options

Google Cloud Messaging APIs offer a broad range of messaging options and capabilities. To help you build an understanding of what you can do with GCM APIs, this page describes the fundamental components of GCM messages and lists some of the most commonly used message options.

Components of a message

The app server builds a downstream message request from these fundamental components: the target, the message options, and the payload. These components are common between the GCM HTTP and XMPP connection server protocols.

Target

Required. When your app server sends a message, it must specify a target that identifies the destination of the message. Specify the target using the field to. This field can contain a single registration token, a topic, or a notification key (for sending to a device group).

Options

The app server can set various options when sending a downstream message to a client app, such as whether that message should be replaced by a subsequent one. For the full list of message options, see the reference information for your chosen connection server protocol, HTTP or XMPP. Commonly used message options are described below.

Payload

For downstream messaging, GCM provides two types of payload: notification and data. Notification is the more lightweight option, with a 2KB limit and a predefined set of user-visible keys. Data payload lets developers send up to 4KB of custom key/value pairs. Notification messages can contain an optional data payload which is delivered when users click on the notification.

Use scenario How to send
Notification GCM automatically displays the message to end user devices on behalf of the client app. Notifications have a pre-defined set of user-visible keys. Set notification payload. May have optional data payload. Always collapsible.
Data Client app is responsible for processing data messages. Data messages have only custom key/value pairs. Set data payload only. Can be either collapsible or non-collapsible.

Use notifications when you want GCM to handle displaying a notification on your client app’s behalf. Use data messages when you want your app to handle the display or process the messages on your Android client app, or if you want to send messages to iOS devices when there is a direct GCM connection.

The app server can send a message including both notification and data payloads. In such cases, GCM handles displaying the notification payload and the client app handles the data payload. For more information and examples, see Notifications and data in the message payload

Notifications and data in the message payload

Notifications provide an easy way for developers to send a user-visible display message with some predefined keys and optional custom key/value pairs. Data payloads include the developer’s custom key/value pairs only, and the client app must handle the message. You can send messages that have both notification and data payloads.

Notifications

To send notifications, set notification with the necessary predefined set of key options for the user-visible part of the notification message. For example, here is a JSON-formatted notification message in an IM application. The user can expect to see a message with the title "Portugal vs. Denmark" and text "great match!" on the device:

  {
    "to" : "bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...",
    "notification" : {
      "body" : "great match!",
      "title" : "Portugal vs. Denmark",
      "icon" : "myicon"
    }
  }

Notifications are delivered to the notification tray when the app is inactive. For an active iOS app, notifications are instead passed to didReceiveRemoteNotification:. For an active Android app, notification payloads are passed to onMessageReceived() under the notification key in the data bundle.

Data messages

Set data with your custom key/value pairs to send a data payload to the client app. Data messages can have a maximum 4KB payload.

For example, here is a JSON-formatted message in the same IM application as above, where the information is encapsulated in data and the client app is expected to interpret the content:

{
   "to" : "bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...",
   "data" : {
     "Nick" : "Mario",
     "body" : "great match!",
     "Room" : "PortugalVSDenmark"
   },
 }

On Android, a client app receives data messages in onMessageReceived() and can handle the key/value pairs accordingly. On iOS, GCM stores the message and delivers it only when the app is in the foreground and has established a GCM connection.

Note these further platform-specific details:

  • On Android, data payload can be retrieved in the Intent used to launch your activity.

  • On iOS, data payload will be found in didReceiveRemoteNotification:.

Hybrid messages with both notification and data payload

App behavior when receiving messages that include both notification and data payloads depends on whether the app is in the background, or the foreground —essentially, whether or not it is active at the time of receipt.

  • When in the background, apps receive the notification payload in the notification tray, and only handle the data payload when the user taps on the notification.
  • When in the foreground, your app receives a bundle with both payloads available.

Here is a JSON-formatted message can containing both notification and data:

  {
    "to" : "APA91bHun4MxP5egoKMwt2KZFBaFUH-1RYqx...",
    "notification" : {
      "body" : "great match!",
      "title" : "Portugal vs. Denmark",
      "icon" : "myicon"
    },
    "data" : {
      "Nick" : "Mario",
      "Room" : "PortugalVSDenmark"
    }
  }

Commonly used message options

This section drills down on some of the options most commonly used when sending simple downstream messages: collapsible messaging, using multiple senders, setting message priority, and setting a lifespan for messages.

Collapsible and non-collapsible messages

Non-collapsible messages

A non-collapsible message implies that each individual message is delivered to the device. A non-collapsible message delivers some useful content, as opposed to a "ping" to the mobile application to contact the server to fetch data. Messages are non-collapsible by default except for notification messages, which are always collapsible. GCM does not guarantee the order of delivery.

Some typical use cases of non-collapsible message are chat messages or critical messages. For example, in an IM application, you would want to deliver every message, because every message has different content.

Note: There is a limit of 100 messages that can be stored without collapsing. If the limit is reached, all stored messages are discarded. When the device is back online, it receives a special message indicating that the limit was reached. The application can then handle the situation properly, typically by requesting a full sync from the app server.

Collapsible messages

A collapsible message is a message that may be replaced by a new message containing the same collapse key if it has yet to be delivered to the device.

Two common use cases of collapsible message are Send-to-Sync messages and notifications. A Send-to-Sync message is a "ping" that tells a mobile application to sync data from the server. An example would be a sports application that updates users with the latest score. Only the most recent message is relevant.

GCM allows a maximum of 4 different collapse keys to be used by the app server per device at any given time. In other words, the GCM connection server can simultaneously store 4 different collapsible send-to-sync messages per device, each with a different collapse key. If you exceed this number GCM will only keep 4 collapse keys, with no guarantees about which ones are kept.

Which should I use?

Collapsible messages are a better choice from a performance standpoint, provided your application doesn't need to use non-collapsible messages. However, if you use collapsible messages, remember that GCM only allows a maximum of 4 different collapse keys to be used by the GCM connection server per registration token at any given time. You must not exceed this number, or it could cause unpredictable consequences.

Use scenario How to send
Non-collapsible Every message is important to the client app and needs to be delivered. Except for notification messages, all messages are non-collapsible by default.
Collapsible When there is a newer message that renders an older, related message irrelevant to the client app, GCM replaces the older message. For example: Send-to-Sync, or outdated notifications. Set the collapse_key parameter.

Setting the priority of a message

You have two options for assigning delivery priority to downstream messages: normal and high priority. Delivery of high and normal priority messages works like this:

  • High priority. This is the default priority for notification messages. GCM attempts to deliver high priority messages immediately, allowing the GCM service to wake a sleeping device when possible and open a network connection to your app server. Apps with instant messaging, chat, or voice call alerts, for example, generally need to open a network connection and make sure GCM delivers the message to the device without delay. Set high priority if the message is time-critical and requires the user’s immediate interaction, and beware that setting your messages to high priority contributes more to battery drain compared to normal priority messages.
  • Normal priority. This is the default priority for data messagesmessages. Normal priority messages won't open network connections on a sleeping device, and their delivery may be delayed to conserve battery. For less time-sensitive messages, such as notifications of new email or other data to sync, choose normal delivery priority.

Valid values are high and normal. For more details, see the server reference for HTTP or XMPP.

For iOS client apps, normal and high priority are analogous to APNs priority levels 5 and 10. For full detail on iOS-specific behavior, see the APNs documentation. For details on Android-specific behavior, see Optimizing for Doze and App Standby.

Here is an example of a normal-priority message to notify a magazine subscriber that new content is available to download:

{
  "to" : "bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...",
  "priority" : "normal",
  "notification" : {
    "body" : "This week’s edition is now available.",
    "title" : "NewsMagazine.com",
    "icon" : "new",
  },
  "data" : {
    "volume" : "3.21.15",
    "contents" : "http://www.news-magazine.com/world-week/21659772"
  }
}

Setting the lifespan of a message

GCM usually delivers messages immediately after they are sent. However, this might not always be possible. For example, if the platform is Android, the device could be turned off, offline, or otherwise unavailable. GCM might intentionally delay messages to prevent an app from consuming excessive resources and negatively affecting battery life.

When this happens, GCM stores the message and delivers it as soon as it's feasible. While this is fine in most cases, there are some applications for which a late message might as well never be delivered. For example, if the message is an incoming call or video chat notification, it will only be meaningful for a small period of time before the call is terminated. Or if the message is an invitation to an event, it will be useless if received after the event has ended.

You can use the time_to_live parameter, supported in both HTTP and XMPP requests, to specify the maximum lifespan of a message. The value of this parameter must be a duration from 0 to 2,419,200 seconds, and it corresponds to the maximum period of time for which GCM will store and try to deliver the message. Requests that don't contain this field default to the maximum period of 4 weeks.

Here are some possible uses for this feature:

  • Video chat incoming calls
  • Expiring invitation events
  • Calendar events

Another advantage of specifying the lifespan of a message is that GCM never throttles messages with a time_to_live value of 0 seconds. In other words, GCM guarantees best effort for messages that must be delivered "now or never." Keep in mind that a time_to_live value of 0 means messages that can't be delivered immediately will be discarded. However, because such messages are never stored, this provides the best latency for sending notifications.

Here is an example of a JSON-formatted request that includes TTL:

 {
   "collapse_key" : "demo",
   "delay_while_idle" : true,
   "to" : "xyz",
   "data" : {
     "key1" : "value1",
     "key2" : "value2",
   },
   "time_to_live" : 3
 },
 

Receiving messages from multi-senders

GCM allows multiple parties to send messages to the same client app. For example, suppose the client app is an articles aggregator with multiple contributors, and each of them should be able to send a message when they publish a new article. This message might contain a URL so that the client app can download the article. Instead of having to centralize all sending activity in one location, GCM gives you the ability to let each of these contributors send its own messages.

To make this possible, make sure each sender generates its own sender ID. See the client documentation for your platform for information on on how to obtain the GCM sender ID. When requesting registration, the client app fetches the token multiple times, each time with a different sender ID in audience field.

Finally, share the registration token with the corresponding app servers (to complete the GCM registration client/server handshake), and they'll be able to send messages to the client app using their own authentication keys.

Note that there is limit of 100 multiple senders.

Lifetime of a message

When an app server posts a message to GCM and receives a message ID back, it does not mean that the message was already delivered to the device. Rather, it means that it was accepted for delivery. What happens to the message after it is accepted depends on many factors.

In the best-case scenario, if the device is connected to GCM, the screen is on and there are no throttling restrictions, the message will be delivered right away.

If the device is connected but in doze mode, a low priority message is stored by GCM until the device is out of doze mode. And that's where the collapse_key flag plays a role: if there is already a message with the same collapse key (and registration token) stored and waiting for delivery, the old message will be discarded and the new message will take its place (that is, the old message will be collapsed by the new one). However, if the collapse key is not set, both the new and old messages are stored for future delivery.

If the device is not connected to GCM, the message will be stored until a connection is established (again respecting the collapse key rules). When a connection is established, GCM delivers all pending messages to the device. If the device never gets connected again (for instance, if it was factory reset), the message will eventually time out and be discarded from GCM storage. The default timeout is 4 weeks, unless the time_to_live flag is set.

Finally, when GCM attempts to deliver a message to the device and the application was uninstalled, GCM will discard that message right away and invalidate the registration token. Future attempts to send a message to that device will result in a NotRegistered error.

Send feedback about...

Cloud Messaging
Cloud Messaging