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.

Send Messages to Topics

GCM topic messaging allows your app server to send a message to multiple devices that have opted in to a particular topic. Based on the publish/subscribe model, topic messaging supports unlimited subscriptions per app. The app server sends messages with payloads up to 2KB to the topic, and GCM handles the message routing and delivers the message reliably to the right devices. For example, users of a weather forecasting app could opt in to a "severe weather alerts" topic and receive notifications of storms threatening specified areas.

Developers can choose any topic name that matches the regular expression, "/topics/[a-zA-Z0-9-_.~%]+". You can configure when to subscribe, when to send messages, and how to handle the notification when it reaches the client app.

Sending topic messages from the server

From the server side, sending messages to a GCM topic is very similar to sending messages to an individual device or to a user group. The app server sets to with /topics/yourTopic. See Notifications and data in the message payload for details on payload support. Examples in this page show how to send data messages to a topic using the HTTP and XMPP protocols.

HTTP POST Request

https://gcm-http.googleapis.com/gcm/send
Content-Type:application/json
Authorization:key=AIzaSyZ-1u...0GBYzPu7Udno5aA

{
  "to": "/topics/foo-bar",
  "data": {
    "message": "This is a GCM Topic Message!",
   }
}

XMPP Message

<message id="">
  <gcm xmlns="google:mobile:data">
  {
      "to": "/topics/foo-bar",
      "message_id": "m-1366082849205" ,
      "data": {
          "message":"This is a GCM Topic Message!"
      }
  }
  </gcm>
</message>

Expect up to 30 seconds of delay before the GCM Connection Server returns a success or failure response to the topic send requests. Make sure to set the app server's timeout value in the request accordingly.

For the full list of message options, see the reference information for your chosen connection server protocol, HTTP or XMPP.

Response format

With the XMPP protocol, the response format for topic messages is identical to basic downstream messages. With HTTP, note that a success response specifies the message_id, while causes of failed messages are referenced in the error field:

//Success example:
{
  "message_id": "10"
}

//failure example:
{
  "error": "TopicsMessageRateExceeded"
}

Managing topic subscriptions on the server

You can take advantage of Instance ID APIs to perform basic topic management tasks from the server side. Given the registration token(s) of client app instances, you can:

In addition to these server-side methods, you can enable client app instances to subscribe to topics from the client side, as described below for Android and iOS clients.

Receiving topic messages on an Android client app

To receive topic messages, each client app needs to obtain a registration token and subscribe to the topic using that token. Note that, for topic messaging it's not required to send the registration token to your app server; however, if you do send it, your server can verify the validity of the token and get more information about the app that created it.

Subscribe to a topic

To subscribe to a topic, the client app calls GCM PubSub subscribe() with the GCM registration token and topic name.

private void subscribeTopics(String token) throws IOException {
    GcmPubSub pubSub = GcmPubSub.getInstance(this);
    for (String topic : TOPICS) {
        pubSub.subscribe(token, "/topics/" + topic, null);
    }
}

To unsubscribe, the client app must call GCM PubSub unsubscribe() with the registration token and topic name.

Receive and handle topic messages

Topic messages are delivered the same way as other GCM messages. On Android, the from field identifies if the message is a topic message and contains the specific topic name.

For example, to provide special handling for topics messages, you could test for "from":"/topics/yourTopic":

@Override
public void onMessageReceived(String from, Bundle data) {
    String message = data.getString("message");
    Log.d(TAG, "From: " + from);
    Log.d(TAG, "Message: " + message);

    if (from.startsWith("/topics/")) {
        // message received from some topic.
    } else {
        // normal downstream message.
    }

    // ...
}

The GCMReceiver and GCMListenerService services simplify message handling on Android client apps. See Receive and handle messages for more information.

Alternatively, developers who choose to not use the new GcmReceiver and GcmListenerService can implement their own GcmBroadcastReceiver to check for topic messages using the from field.

Receiving topic messages on an iOS client app

To receive topic messages, each client app needs to obtain a registration token and subscribe to the topic using that token. Note that, for topic messaging it's not required to send the registration token to your app server; however, if you do send it, your server can verify the validity of the token and get more information about the app that created it.

Subscribe to a topic

GCMPubSub.h handles topic messaging functionality. Use [GCMPubSub sharedInstance] to access a GCM PubSub instance after starting the GCM Service.

To subscribe to a topic, call subscribeWithToken:token:topic:options:handler from your application’s main thread (GCM is not thread safe). This makes an asynchronous request to the GCM backend and subscribes the client to the given topic. When the request finishes, the handler is invoked with a nil error object in case of success, or a valid error object in case of failure.

[[GCMPubSub sharedInstance] subscribeWithToken:yourRegToken
                                         topic:@"/topics/sample-topic"
                                       options:nil
                                       handler:^void(NSError *error) {
                                         if (error) {
                                           int code = error.code;
                                           // handle the error, perform exponential backoff
                                           // to retry
                                         } else {
                                           // subscribe successful
                                         }
                                       }];

The handler is invoked once the request has been processed. If the topic subscription succeeds, the NSError object is nil. If there is failure, NSError contains the failure reason. For more information, see Error codes.

To unsubscribe, the client app calls unsubscribeWithToken:token:topic:options:handler from your application’s main thread asynchronously with registration token and topic name. Similar to subscribe, the handler is invoked once the request has been processed with the corresponding status.

[[GCMPubSub sharedInstance] unsubscribeWithToken:yourRegToken
                                           topic:@"/topics/sample-topic"
                                         options:nil
                                         handler:^void(NSError *error) {
                                           if (error) {
                                             int code = error.code;
                                             // handle the error, using exponential backoff to retry
                                           } else {
                                             // Unsubscribe successfully
                                           }
                                         }];

Receive and handle topic messages

Topic messages are delivered the same way as other GCM messages. See Receive and handle messages for more information about the scenarios when client app should implement application:didReceiveRemoteNotification: .

Topic messaging errors

These are the errors you might encounter while sending messages to topics:

Error Description Recommended Action
INVALID_PARAMETERS Indicates invalid input parameters. Check that the parameters passed to the function are valid and correct.
TOO_MANY_TOPICS Returned when a single app instance subscribes to an excessive number of topics. Reduce number of subscriptions per app instance. Investigate whether the number of subscriptions is intentional.

Send feedback about...

Cloud Messaging
Cloud Messaging