“GCM topic messaging allows your app server to send a message to multiple devices that have opted into 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.
GCM introduces topic messaging, a way of sending messages to many clients.
An application can create one or more topics and register clients to each topic. Then messages are sent for a specific topic, GCM informing all clients who have been registered for it. This way one can reach a large number of clients, even all of them.
Developers can choose any topic name that matches the regular expression, "/topics/[a-zA-Z0-9-_.~%]+"
How to Send the topic messages from the server
GCM topic is very similar to sending messages to an individual device.
The app server sets to
with /topics/yourTopicMessage
We can send data messages to a topic by HTTP and XMPP protocols.
HTTP POST Request:
1 2 3 4 5 6 7 8 9 10 |
https://gcm-http.googleapis.com/gcm/send Content-Type:application/json Authorization:key=AIzaSyDaIaL....3gOx_YQgTxWpQ { "to": "/topics/mobikul", "data": { "message": "This is a GCM Topic Message by mobikul", } } |
XMPP Message:
1 2 3 4 5 6 7 8 9 10 11 |
<message id=""> <gcm xmlns="google:mobile:data"> { "to": "/topics/mobikul", "message_id": "m-1363452849222" , "data": { "message":"This is a GCM Topic Message by mobikul" } } </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.
How to Subscribe to a topic
To subscribe to a topic, the client app calls GCM PubSub subscribe()
with the GCM registration token and topic name.
1 2 3 4 5 6 |
private void subscribeTopics(String token) throws IOException { GcmPubSub pubSub = GcmPubSub.getInstance(this); for (String topic : TOPICS) { pubSub.subscribe(token, "/topics/" + topic, null); } } |
How to receive and handle topic messages
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
@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 is simplify use for message handling on Android client apps.