From 6b4c3fed885db4341076159dc549d6bdae4df02e Mon Sep 17 00:00:00 2001
From: Joe Fernandez Android Cloud to Device Messaging (C2DM) was officially deprecated on June 26, 2012, and will be
- shut down completely as of July 30, 2015. C2DM developers are strongly encouraged to move
- to Google Cloud Messaging (GCM). GCM is the next generation of C2DM. This document is addressed to C2DM developers who are moving to GCM. It describes the differences between GCM and C2DM, and explains how to migrate existing C2DM apps to GCM. C2DM was launched in 2010 to help Android apps send data from servers to their applications. Servers can tell apps to contact the server directly, to fetch updated application or user data. The C2DM service handles all aspects of queueing of messages and delivery to the target application running on the target device. GCM replaces C2DM. The focus of GCM is as follows: GCM builds on the core foundation of C2DM. Here is what's different: C2DM and GCM are not interoperable. For example, you cannot post notifications from GCM to C2DM registration IDs, nor can you use C2DM registration IDs as GCM registration IDs. From your server-side application, you must keep track of whether a registration ID is from C2DM or GCM and use the proper endpoint. As you transition from C2DM to GCM, your server needs to be aware of whether a given registration ID
-contains an old C2DM sender or a new GCM project number. This is the approach we recommend: have the new app version (the one that uses GCM) send a bit along with the registration ID. This bit tells your server that this registration ID is for GCM. If you don't get the extra bit, you mark the registration ID as C2DM. Once no more valid registration IDs are marked as C2DM, you can complete the migration. This section describes how to move existing C2DM apps to GCM. Migration is simple! Just re-register the client app for your target GCM-enabled platform. For
- example, see Register for GCM After receiving a response from GCM, the registration ID obtained must be sent to the application server. When doing this, the application should indicate that it is sending a GCM registration ID so that the server can distinguish it from existing C2DM registrations. When the application server receives a GCM registration ID, it should store it and mark it as such. Sending messages to GCM devices requires a few changes: For example:
- For a detailed discussion of this topic and more examples, see the Architectural Overview. Eventually, once enough users of your application have migrated to the new service, you might want to take advantage of the new JSON-formatted requests that give access to the full set of features provided by GCM. The Google Cloud Messaging (GCM) Cloud Connection Server (CCS) is an XMPP endpoint that provides a
-persistent, asynchronous, bidirectional connection to Google servers. The
-connection can be used to send and receive messages between your server and
-your users' GCM-connected devices. Note: The content in this document
-applies to
-GCM with Chrome apps as well as Android.
-
- You can continue to use the HTTP request mechanism to send messages to GCM
-servers, side-by-side with CCS which uses XMPP. Some of the benefits of CCS include: The upstream messaging (device-to-cloud) feature of CCS is part of the Google
-Play services platform. Upstream messaging is available through the
-
-{@code GoogleCloudMessaging}
-APIs. For examples, see
-Implementing an XMPP-based App Server. Note: See the
-Server Reference for a list of all the message
-parameters and which connection server(s) supports them. CCS just uses XMPP as an authenticated transport layer, so you can use most
-XMPP libraries to manage the connection. For an example, see
-Java sample using the Smack library. The CCS XMPP endpoint runs at {@code gcm.googleapis.com:5235}. When testing
-functionality (with non-production users), you should instead connect to
-{@code gcm-preprod.googleapis.com:5236} (note the different port). Regular
-testing on preprod (a smaller environment where the latest CCS builds run) is
-beneficial both for isolating real users from test code, as well as for early
-detection of unexpected behavior changes. Note that a connection receives upstream
-messages destined for its GCM sender ID, regardless of which environment (gcm or
-gcm-preprod) it is connected to. Therefore, test code connecting to
-{@code gcm-preprod.googleapis.com:5236} should use a different GCM sender ID to
-avoid upstream messages from production traffic being sent over test connections. The connection has two important requirements: If at any point the connection fails, you should immediately reconnect.
-There is no need to back off after a disconnect that happens after
-authentication. The following snippets illustrate how to perform authentication in CCS. Once the XMPP connection is established, CCS and your server use normal XMPP
- The JSON payload for regular GCM messages is similar to
-what the GCM http endpoint uses, with these
-exceptions: In addition to regular GCM messages, control messages are sent, indicated by
-the {@code message_type} field in the JSON object. The value can be either
-'ack' or 'nack', or 'control' (see formats below). Any GCM message with an
-unknown {@code message_type} can be ignored by your server. For each device message your app server receives from CCS, it needs to send
-an ACK message.
-It never needs to send a NACK message. If you don't send an ACK for a message,
-CCS resends it the next time a new XMPP connection is established, unless the
-message expires first.
- CCS also sends an ACK or NACK for each server-to-device message. If you do not
-receive either, it means that the TCP connection was closed in the middle of the
-operation and your server needs to resend the messages. See
-Flow Control for details.
- Note: See the
-Server Reference for a list of all the message
-parameters and which connection server(s) supports them. Here is an XMPP stanza containing the JSON message from a 3rd-party app server to CCS:
-
- A CCS response can have 3 possible forms. The first one is a regular 'ack'
-message. But when the response contains an error, there are 2
-different forms the message can take, described below. Here is an XMPP stanza containing the ACK/NACK message from CCS to 3rd-party app server:
- A NACK error is a regular XMPP message in which the {@code message_type} status
-message is "nack". A NACK message contains: Below are some examples. Bad registration: Invalid JSON: Device Message Rate Exceeded: See the Server Reference for a complete list of the
-NACK error codes. Unless otherwise
-indicated, a NACKed message should not be retried. Unexpected NACK error codes
-should be treated the same as {@code INTERNAL_SERVER_ERROR}. You can also get a stanza error in certain cases.
-A stanza error contains: For example: Periodically, CCS needs to close down a connection to perform load balancing. Before it
-closes the connection, CCS sends a {@code CONNECTION_DRAINING} message to indicate that the connection is being drained
-and will be closed soon. "Draining" refers to shutting off the flow of messages coming into a
-connection, but allowing whatever is already in the pipeline to continue. When you receive
-a {@code CONNECTION_DRAINING} message, you should immediately begin sending messages to another CCS
-connection, opening a new connection if necessary. You should, however, keep the original
-connection open and continue receiving messages that may come over the connection (and
-ACKing them)—CCS handles initiating a connection close when it is ready. The {@code CONNECTION_DRAINING} message looks like this: {@code CONNECTION_DRAINING} is currently the only {@code control_type} supported. You can get delivery receipts (sent from CCS to
-your 3rd party app server) when
-a device confirms that it received a message sent by CCS. To enable this feature, the message your 3rd-party app server sends to CCS must include
-a field called Here is an XMPP stanza containing a JSON
-message with Here is an example of the delivery receipt that CCS sends to tell your 3rd-party
-app server that a device received a message that CCS sent it:Quickview
-
-
-
-
-
-In this document
-
-
-
-Historical Overview
-
-
-How is GCM Different from C2DM?
-
-
-
-collapse_key
parameter and messages will not be collapsed. GCM will store up to 100 messages. If you exceed that number, all messages will be discarded but you will receive a special message. If an application receives this message, it needs to sync with the server. For more information, see Advanced Topics.Relationship between C2DM and GCM
-
-Migrating Your Apps
-Client changes
-Server changes
-
-
-https://android.googleapis.com/gcm/send
.Content-Type:application/json
-Authorization:key=AIzaSyB-1uEai2WiUapxCs2Q0GZYzPu7Udno5aA
-
-{
- "registration_id" : "APA91bHun4MxP5egoKMwt2KZFBaFUH-1RYqx...",
- "data" : {
- "Team" : "Portugal",
- "Score" : "3",
- "Player" : "Varela",
- },
-}
-In this document
-
-
-
-
-
-
- See Also
-
-
-
-
-
-
-Establishing a Connection
-
-
-
-
-Authentication
-
-Client
-<stream:stream to="gcm.googleapis.com"
- version="1.0" xmlns="jabber:client"
- xmlns:stream="http://etherx.jabber.org/streams"/>
-
-Server
-<str:features xmlns:str="http://etherx.jabber.org/streams">
- <mechanisms xmlns="urn:ietf:params:xml:ns:xmpp-sasl">
- <mechanism>X-OAUTH2</mechanism>
- <mechanism>X-GOOGLE-TOKEN</mechanism>
- <mechanism>PLAIN</mechanism>
- </mechanisms>
-</str:features>
-
-
-Client
-<auth mechanism="PLAIN"
-xmlns="urn:ietf:params:xml:ns:xmpp-sasl">MTI2MjAwMzQ3OTMzQHByb2plY3RzLmdjbS5hb
-mFTeUIzcmNaTmtmbnFLZEZiOW1oekNCaVlwT1JEQTJKV1d0dw==</auth>
-
-
-Server
-<success xmlns="urn:ietf:params:xml:ns:xmpp-sasl"/>
-
-Downstream Messages
-<message>
stanzas to send JSON-encoded messages back and
-forth. The body of the <message>
must be:
-<gcm xmlns:google:mobile:data>
- JSON payload
-</gcm>
-
-
-
-
-
-Request format
-
-<message id="">
- <gcm xmlns="google:mobile:data">
- {
- "to":"REGISTRATION_ID", // "to" replaces "registration_ids"
- "message_id":"m-1366082849205" // new required field
- "data":
- {
- "hello":"world",
- }
- "time_to_live":"600",
- "delay_while_idle": true/false,
- "delivery_receipt_requested": true/false
- }
- </gcm>
-</message>
-
-
-Response format
-
-ACK message
-
-<message id="">
- <gcm xmlns="google:mobile:data">
- {
- "from":"REGID",
- "message_id":"m-1366082849205"
- "message_type":"ack"
- }
- </gcm>
-</message>
-
-
-NACK message
-
-
-
-
-<message>
- <gcm xmlns="google:mobile:data">
- {
- "message_type":"nack",
- "message_id":"msgId1",
- "from":"SomeInvalidRegistrationId",
- "error":"BAD_REGISTRATION",
- "error_description":"Invalid token on 'to' field: SomeInvalidRegistrationId"
- }
- </gcm>
-</message>
-
-<message>
- <gcm xmlns="google:mobile:data">
- {
- "message_type":"nack",
- "message_id":"msgId1",
- "from":"APA91bHFOtaQGSwupt5l1og",
- "error":"INVALID_JSON",
- "error_description":"InvalidJson: JSON_TYPE_ERROR : Field \"time_to_live\" must be a JSON java.lang.Number: abc"
- }
- </gcm>
-</message>
-
-
-<message id="...">
- <gcm xmlns="google:mobile:data">
- {
- "message_type":"nack",
- "message_id":"msgId1",
- "from":"REGID",
- "error":"DEVICE_MESSAGE_RATE_EXCEEDED",
- "error_description":"Downstream message rate exceeded for this registration id"
- }
- </gcm>
-</message>
-
-
-Stanza error
-
-
-
-<message id="3" type="error" to="123456789@gcm.googleapis.com/ABC">
- <gcm xmlns="google:mobile:data">
- {"random": "text"}
- </gcm>
- <error code="400" type="modify">
- <bad-request xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"/>
- <text xmlns="urn:ietf:params:xml:ns:xmpp-stanzas">
- InvalidJson: JSON_PARSING_ERROR : Missing Required Field: message_id\n
- </text>
- </error>
-</message>
-
-
-Control messages
-
-<message>
- <data:gcm xmlns:data="google:mobile:data">
- {
- "message_type":"control"
- "control_type":"CONNECTION_DRAINING"
- }
- </data:gcm>
-</message>
-
-Receive delivery receipts
-
-"delivery_receipt_requested"
. When this field is set to
-true
, CCS sends a delivery receipt when a device confirms that it received a particular message."delivery_receipt_requested"
set to true
:<message id="">
- <gcm xmlns="google:mobile:data">
- {
- "to":"REGISTRATION_ID",
- "message_id":"m-1366082849205"
- "data":
- {
- "hello":"world",
- }
- "time_to_live":"600",
- "delay_while_idle": true,
- "delivery_receipt_requested": true
- }
- </gcm>
-</message>
-
-
-
-
-
<message id=""> - <gcm xmlns="google:mobile:data"> - { - "category":"com.example.yourapp", // to know which app sent it - "data": - { - “message_status":"MESSAGE_SENT_TO_DEVICE", - “original_message_id”:”m-1366082849205” - “device_registration_id”: “REGISTRATION_ID” - }, - "message_id":"dr2:m-1366082849205", - "message_type":"receipt", - "from":"gcm.googleapis.com" - } - </gcm> -</message>- -
Note the following:
- -dr2:
prefix. Your 3rd-party app server must send an ACK back with this ID,
-which in this example is {@code dr2:m-1366082849205}.Using CCS and the - -{@code GoogleCloudMessaging} -API, you can send messages from a user's device to the cloud.
- -Here is how you send an upstream message using the - -{@code GoogleCloudMessaging} -API. For a complete example, see Implementing GCM Client:
- -GoogleCloudMessaging gcm = GoogleCloudMessaging.get(context); -String GCM_SENDER_ID = "Your-Sender-ID"; -AtomicInteger msgId = new AtomicInteger(); -String id = Integer.toString(msgId.incrementAndGet()); -Bundle data = new Bundle(); -// Bundle data consists of a key-value pair -data.putString("hello", "world"); -// "time to live" parameter -// This is optional. It specifies a value in seconds up to 24 hours. -int ttl = [0 seconds, 24 hours] - -gcm.send(GCM_SENDER_ID + "@gcm.googleapis.com", id, ttl, data); -- -
This call generates the necessary XMPP stanza for sending the upstream message. -The message goes from the app on the device to CCS to the 3rd-party app server. -The stanza has the following format:
- -<message id=""> - <gcm xmlns="google:mobile:data"> - { - "category":"com.example.yourapp", // to know which app sent it - "data": - { - "hello":"world", - }, - "message_id":"m-123", - "from":"REGID" - } - </gcm> -</message>- -
Here is the format of the ACK expected by CCS from 3rd-party app servers in -response to the above message:
- -<message id=""> - <gcm xmlns="google:mobile:data"> - { - "to":"REGID", - "message_id":"m-123" - "message_type":"ack" - } - </gcm> -</message>- - -
Every message sent to CCS receives either an ACK or a NACK response. Messages -that haven't received one of these responses are considered pending. If the pending -message count reaches 100, the 3rd-party app server should stop sending new messages -and wait for CCS to acknowledge some of the existing pending messages as illustrated in -figure 1:
- - - - - -Conversely, to avoid overloading the 3rd-party app server, CCS stops sending -if there are too many unacknowledged messages. Therefore, the 3rd-party app server -should "ACK" upstream messages, received from the client application via CCS, as soon as possible -to maintain a constant flow of incoming messages. The aforementioned pending message limit doesn't -apply to these ACKs. Even if the pending message count reaches 100, the 3rd-party app server -should continue sending ACKs for messages received from CCS to avoid blocking delivery of new -upstream messages.
- -ACKs are only valid within the context of one connection. If the connection is -closed before a message can be ACKed, the 3rd-party app server should wait for CCS -to resend the upstream message before ACKing it again. Similarly, all pending messages for which an -ACK/NACK was not received from CCS before the connection was closed should be sent again. -
- -This section gives examples of implementing an app server that works with CCS. -Note that a full GCM implementation requires a client-side implementation, in -addition to the server. For more information, see -Implementing GCM Client. - -
Here is a sample app server written in Java, using the -Smack library.
- -import org.jivesoftware.smack.ConnectionConfiguration; -import org.jivesoftware.smack.ConnectionConfiguration.SecurityMode; -import org.jivesoftware.smack.ConnectionListener; -import org.jivesoftware.smack.PacketInterceptor; -import org.jivesoftware.smack.PacketListener; -import org.jivesoftware.smack.SmackException; -import org.jivesoftware.smack.SmackException.NotConnectedException; -import org.jivesoftware.smack.XMPPConnection; -import org.jivesoftware.smack.XMPPException; -import org.jivesoftware.smack.filter.PacketTypeFilter; -import org.jivesoftware.smack.packet.DefaultPacketExtension; -import org.jivesoftware.smack.packet.Message; -import org.jivesoftware.smack.packet.Packet; -import org.jivesoftware.smack.packet.PacketExtension; -import org.jivesoftware.smack.provider.PacketExtensionProvider; -import org.jivesoftware.smack.provider.ProviderManager; -import org.jivesoftware.smack.tcp.XMPPTCPConnection; -import org.jivesoftware.smack.util.StringUtils; -import org.json.simple.JSONValue; -import org.json.simple.parser.ParseException; -import org.xmlpull.v1.XmlPullParser; - -import java.io.IOException; -import java.util.HashMap; -import java.util.Map; -import java.util.UUID; -import java.util.logging.Level; -import java.util.logging.Logger; - -import javax.net.ssl.SSLSocketFactory; - -/** - * Sample Smack implementation of a client for GCM Cloud Connection Server. This - * code can be run as a standalone CCS client. - * - * <p>For illustration purposes only. - */ -public class SmackCcsClient { - - private static final Logger logger = Logger.getLogger("SmackCcsClient"); - - private static final String GCM_SERVER = "gcm.googleapis.com"; - private static final int GCM_PORT = 5235; - - private static final String GCM_ELEMENT_NAME = "gcm"; - private static final String GCM_NAMESPACE = "google:mobile:data"; - - static { - - ProviderManager.addExtensionProvider(GCM_ELEMENT_NAME, GCM_NAMESPACE, - new PacketExtensionProvider() { - @Override - public PacketExtension parseExtension(XmlPullParser parser) throws - Exception { - String json = parser.nextText(); - return new GcmPacketExtension(json); - } - }); - } - - private XMPPConnection connection; - - /** - * Indicates whether the connection is in draining state, which means that it - * will not accept any new downstream messages. - */ - protected volatile boolean connectionDraining = false; - - /** - * Sends a downstream message to GCM. - * - * @return true if the message has been successfully sent. - */ - public boolean sendDownstreamMessage(String jsonRequest) throws - NotConnectedException { - if (!connectionDraining) { - send(jsonRequest); - return true; - } - logger.info("Dropping downstream message since the connection is draining"); - return false; - } - - /** - * Returns a random message id to uniquely identify a message. - * - * <p>Note: This is generated by a pseudo random number generator for - * illustration purpose, and is not guaranteed to be unique. - */ - public String nextMessageId() { - return "m-" + UUID.randomUUID().toString(); - } - - /** - * Sends a packet with contents provided. - */ - protected void send(String jsonRequest) throws NotConnectedException { - Packet request = new GcmPacketExtension(jsonRequest).toPacket(); - connection.sendPacket(request); - } - - /** - * Handles an upstream data message from a device application. - * - * <p>This sample echo server sends an echo message back to the device. - * Subclasses should override this method to properly process upstream messages. - */ - protected void handleUpstreamMessage(Map<String, Object> jsonObject) { - // PackageName of the application that sent this message. - String category = (String) jsonObject.get("category"); - String from = (String) jsonObject.get("from"); - @SuppressWarnings("unchecked") - Map<String, String> payload = (Map<String, String>) jsonObject.get("data"); - payload.put("ECHO", "Application: " + category); - - // Send an ECHO response back - String echo = createJsonMessage(from, nextMessageId(), payload, - "echo:CollapseKey", null, false); - - try { - sendDownstreamMessage(echo); - } catch (NotConnectedException e) { - logger.log(Level.WARNING, "Not connected anymore, echo message is - not sent", e); - } - } - - /** - * Handles an ACK. - * - * <p>Logs a {@code INFO} message, but subclasses could override it to - * properly handle ACKs. - */ - protected void handleAckReceipt(Map<String, Object> jsonObject) { - String messageId = (String) jsonObject.get("message_id"); - String from = (String) jsonObject.get("from"); - logger.log(Level.INFO, "handleAckReceipt() from: " + from + ", - messageId: " + messageId); - } - - /** - * Handles a NACK. - * - * <p>Logs a {@code INFO} message, but subclasses could override it to - * properly handle NACKs. - */ - protected void handleNackReceipt(Map<String, Object> jsonObject) { - String messageId = (String) jsonObject.get("message_id"); - String from = (String) jsonObject.get("from"); - logger.log(Level.INFO, "handleNackReceipt() from: " + from + ", - messageId: " + messageId); - } - - protected void handleControlMessage(Map<String, Object> jsonObject) { - logger.log(Level.INFO, "handleControlMessage(): " + jsonObject); - String controlType = (String) jsonObject.get("control_type"); - if ("CONNECTION_DRAINING".equals(controlType)) { - connectionDraining = true; - } else { - logger.log(Level.INFO, "Unrecognized control type: %s. This could - happen if new features are " + "added to the CCS protocol.", - controlType); - } - } - - /** - * Creates a JSON encoded GCM message. - * - * @param to RegistrationId of the target device (Required). - * @param messageId Unique messageId for which CCS sends an - * "ack/nack" (Required). - * @param payload Message content intended for the application. (Optional). - * @param collapseKey GCM collapse_key parameter (Optional). - * @param timeToLive GCM time_to_live parameter (Optional). - * @param delayWhileIdle GCM delay_while_idle parameter (Optional). - * @return JSON encoded GCM message. - */ - public static String createJsonMessage(String to, String messageId, - Map<String, String> payload, String collapseKey, Long timeToLive, - Boolean delayWhileIdle) { - Map<String, Object> message = new HashMap<String, Object>(); - message.put("to", to); - if (collapseKey != null) { - message.put("collapse_key", collapseKey); - } - if (timeToLive != null) { - message.put("time_to_live", timeToLive); - } - if (delayWhileIdle != null && delayWhileIdle) { - message.put("delay_while_idle", true); - } - message.put("message_id", messageId); - message.put("data", payload); - return JSONValue.toJSONString(message); - } - - /** - * Creates a JSON encoded ACK message for an upstream message received - * from an application. - * - * @param to RegistrationId of the device who sent the upstream message. - * @param messageId messageId of the upstream message to be acknowledged to CCS. - * @return JSON encoded ack. - */ - protected static String createJsonAck(String to, String messageId) { - Map<String, Object> message = new HashMap<String, Object>(); - message.put("message_type", "ack"); - message.put("to", to); - message.put("message_id", messageId); - return JSONValue.toJSONString(message); - } - - /** - * Connects to GCM Cloud Connection Server using the supplied credentials. - * - * @param senderId Your GCM project number - * @param apiKey API Key of your project - */ - public void connect(long senderId, String apiKey) - throws XMPPException, IOException, SmackException { - ConnectionConfiguration config = - new ConnectionConfiguration(GCM_SERVER, GCM_PORT); - config.setSecurityMode(SecurityMode.enabled); - config.setReconnectionAllowed(true); - config.setRosterLoadedAtLogin(false); - config.setSendPresence(false); - config.setSocketFactory(SSLSocketFactory.getDefault()); - - connection = new XMPPTCPConnection(config); - connection.connect(); - - connection.addConnectionListener(new LoggingConnectionListener()); - - // Handle incoming packets - connection.addPacketListener(new PacketListener() { - - @Override - public void processPacket(Packet packet) { - logger.log(Level.INFO, "Received: " + packet.toXML()); - Message incomingMessage = (Message) packet; - GcmPacketExtension gcmPacket = - (GcmPacketExtension) incomingMessage. - getExtension(GCM_NAMESPACE); - String json = gcmPacket.getJson(); - try { - @SuppressWarnings("unchecked") - Map<String, Object> jsonObject = - (Map<String, Object>) JSONValue. - parseWithException(json); - - // present for "ack"/"nack", null otherwise - Object messageType = jsonObject.get("message_type"); - - if (messageType == null) { - // Normal upstream data message - handleUpstreamMessage(jsonObject); - - // Send ACK to CCS - String messageId = (String) jsonObject.get("message_id"); - String from = (String) jsonObject.get("from"); - String ack = createJsonAck(from, messageId); - send(ack); - } else if ("ack".equals(messageType.toString())) { - // Process Ack - handleAckReceipt(jsonObject); - } else if ("nack".equals(messageType.toString())) { - // Process Nack - handleNackReceipt(jsonObject); - } else if ("control".equals(messageType.toString())) { - // Process control message - handleControlMessage(jsonObject); - } else { - logger.log(Level.WARNING, - "Unrecognized message type (%s)", - messageType.toString()); - } - } catch (ParseException e) { - logger.log(Level.SEVERE, "Error parsing JSON " + json, e); - } catch (Exception e) { - logger.log(Level.SEVERE, "Failed to process packet", e); - } - } - }, new PacketTypeFilter(Message.class)); - - // Log all outgoing packets - connection.addPacketInterceptor(new PacketInterceptor() { - @Override - public void interceptPacket(Packet packet) { - logger.log(Level.INFO, "Sent: {0}", packet.toXML()); - } - }, new PacketTypeFilter(Message.class)); - - connection.login(senderId + "@gcm.googleapis.com", apiKey); - } - - public static void main(String[] args) throws Exception { - final long senderId = 1234567890L; // your GCM sender id - final String password = "Your API key"; - - SmackCcsClient ccsClient = new SmackCcsClient(); - - ccsClient.connect(senderId, password); - - // Send a sample hello downstream message to a device. - String toRegId = "RegistrationIdOfTheTargetDevice"; - String messageId = ccsClient.nextMessageId(); - Map<String, String> payload = new HashMap<String, String>(); - payload.put("Hello", "World"); - payload.put("CCS", "Dummy Message"); - payload.put("EmbeddedMessageId", messageId); - String collapseKey = "sample"; - Long timeToLive = 10000L; - String message = createJsonMessage(toRegId, messageId, payload, - collapseKey, timeToLive, true); - - ccsClient.sendDownstreamMessage(message); - } - - /** - * XMPP Packet Extension for GCM Cloud Connection Server. - */ - private static final class GcmPacketExtension extends DefaultPacketExtension { - - private final String json; - - public GcmPacketExtension(String json) { - super(GCM_ELEMENT_NAME, GCM_NAMESPACE); - this.json = json; - } - - public String getJson() { - return json; - } - - @Override - public String toXML() { - return String.format("<%s xmlns=\"%s\">%s</%s>", - GCM_ELEMENT_NAME, GCM_NAMESPACE, - StringUtils.escapeForXML(json), GCM_ELEMENT_NAME); - } - - public Packet toPacket() { - Message message = new Message(); - message.addExtension(this); - return message; - } - } - - private static final class LoggingConnectionListener - implements ConnectionListener { - - @Override - public void connected(XMPPConnection xmppConnection) { - logger.info("Connected."); - } - - @Override - public void authenticated(XMPPConnection xmppConnection) { - logger.info("Authenticated."); - } - - @Override - public void reconnectionSuccessful() { - logger.info("Reconnecting.."); - } - - @Override - public void reconnectionFailed(Exception e) { - logger.log(Level.INFO, "Reconnection failed.. ", e); - } - - @Override - public void reconnectingIn(int seconds) { - logger.log(Level.INFO, "Reconnecting in %d secs", seconds); - } - - @Override - public void connectionClosedOnError(Exception e) { - logger.info("Connection closed on error."); - } - - @Override - public void connectionClosed() { - logger.info("Connection closed."); - } - } -}- -
Here is an example of a CCS app server written in Python. This sample echo -server sends an initial message, and for every upstream message received, it sends -a dummy response back to the application that sent the upstream message. This -example illustrates how to connect, send, and receive GCM messages using XMPP. It -shouldn't be used as-is on a production deployment.
- --#!/usr/bin/python -import sys, json, xmpp, random, string - -SERVER = 'gcm.googleapis.com' -PORT = 5235 -USERNAME = "Your GCM Sender Id" -PASSWORD = "API Key" -REGISTRATION_ID = "Registration Id of the target device" - -unacked_messages_quota = 100 -send_queue = [] - -# Return a random alphanumerical id -def random_id(): - rid = '' - for x in range(8): rid += random.choice(string.ascii_letters + string.digits) - return rid - -def message_callback(session, message): - global unacked_messages_quota - gcm = message.getTags('gcm') - if gcm: - gcm_json = gcm[0].getData() - msg = json.loads(gcm_json) - if not msg.has_key('message_type'): - # Acknowledge the incoming message immediately. - send({'to': msg['from'], - 'message_type': 'ack', - 'message_id': msg['message_id']}) - # Queue a response back to the server. - if msg.has_key('from'): - # Send a dummy echo response back to the app that sent the upstream message. - send_queue.append({'to': msg['from'], - 'message_id': random_id(), - 'data': {'pong': 1}}) - elif msg['message_type'] == 'ack' or msg['message_type'] == 'nack': - unacked_messages_quota += 1 - -def send(json_dict): - template = ("<message><gcm xmlns='google:mobile:data'>{1}</gcm></message>") - client.send(xmpp.protocol.Message( - node=template.format(client.Bind.bound[0], json.dumps(json_dict)))) - -def flush_queued_messages(): - global unacked_messages_quota - while len(send_queue) and unacked_messages_quota > 0: - send(send_queue.pop(0)) - unacked_messages_quota -= 1 - -client = xmpp.Client('gcm.googleapis.com', debug=['socket']) -client.connect(server=(SERVER,PORT), secure=1, use_srv=False) -auth = client.auth(USERNAME, PASSWORD) -if not auth: - print 'Authentication failed!' - sys.exit(1) - -client.RegisterHandler('message', message_callback) - -send_queue.append({'to': REGISTRATION_ID, - 'message_id': 'reg_id', - 'data': {'message_destination': 'RegId', - 'message_id': random_id()}}) - -while True: - client.Process(1) - flush_queued_messages()diff --git a/docs/html/google/gcm/client.jd b/docs/html/google/gcm/client.jd deleted file mode 100644 index 9cb3f84..0000000 --- a/docs/html/google/gcm/client.jd +++ /dev/null @@ -1,689 +0,0 @@ -page.title=Implementing GCM Client on Android -page.tags=cloud,push,messaging -@jd:body - -
A Google Cloud Messaging (GCM) Android client is a GCM-enabled app that runs on an -Android device. To write your client code, we recommend that you use the - -{@code GoogleCloudMessaging} API.
- -Here are the requirements for running a GCM Android client:
- -A full GCM implementation requires both a client implementation and a server -implementation. For more -information about implementing the server side, see -Implementing GCM Server.
- -The following sections walk you through the steps involved in writing a GCM -client-side application. Your client app can be arbitrarily complex, but at bare -minimum, a GCM client app must include code to register (and thereby get a -registration ID), and a broadcast receiver to receive messages sent by GCM. -
- -To write your client application, use the - -{@code GoogleCloudMessaging} API. -To use this API, you must set up your project to use the Google Play services SDK, -as described in Setup Google Play -Services SDK.
- -Caution: When you add the Play Services library to -your project, be sure to add it with resources, as described in - -Setup Google Play Services SDK. The key point is that you must -reference the library—simply adding a {@code .jar} file to -your Eclipse project will not work. You must follow the directions -for referencing a library, or your app won't be able to access -the library's resources, and it won't run properly. -If you're using Android Studio, this is the string to add to the -{@code dependency} section of your application's {@code build.gradle} file:
- -dependencies { - compile "com.google.android.gms:play-services:3.1.+" -} -- - -
Add the following to your application's manifest:
-com.google.android.c2dm.permission.RECEIVE
permission so
-the Android application can register and receive messages.android.permission.INTERNET
permission so the Android
-application can send the registration ID to the 3rd party server.android.permission.WAKE_LOCK
permission so the application
-can keep the processor from sleeping when a message is received. Optional—use
-only if the app wants to keep the device from sleeping.applicationPackage + ".permission.C2D_MESSAGE"
-permission to prevent other Android applications from registering and receiving
-the Android application's messages. The permission name must exactly match this
-pattern—otherwise the Android application will not receive the messages.com.google.android.c2dm.intent.RECEIVE
, with
-the category set
-as applicationPackage
. The receiver should require the
-com.google.android.c2dm.permission.SEND
permission, so that only the GCM
-Framework can send a message to it. If your app uses an {@link android.app.IntentService}
-(not required, but a common pattern), this receiver should be an instance of
-{@link android.support.v4.content.WakefulBroadcastReceiver}.
-A {@link android.support.v4.content.WakefulBroadcastReceiver} takes care of
-creating and managing a
-
-partial wake lock for your app.android:minSdkVersion="8"
or higher in the manifest. This
-ensures that the Android application cannot be installed in an environment in which it
-could not run properly. Here are excerpts from a sample manifest that supports GCM:
- --<manifest package="com.example.gcm" ...> - - <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="17"/> - <uses-permission android:name="android.permission.INTERNET" /> - <uses-permission android:name="android.permission.GET_ACCOUNTS" /> - <uses-permission android:name="android.permission.WAKE_LOCK" /> - <uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" /> - - <permission android:name="com.example.gcm.permission.C2D_MESSAGE" - android:protectionLevel="signature" /> - <uses-permission android:name="com.example.gcm.permission.C2D_MESSAGE" /> - - <application ...> - <receiver - android:name=".GcmBroadcastReceiver" - android:permission="com.google.android.c2dm.permission.SEND" > - <intent-filter> - <action android:name="com.google.android.c2dm.intent.RECEIVE" /> - <category android:name="com.example.gcm" /> - </intent-filter> - </receiver> - <service android:name=".GcmIntentService" /> - </application> - -</manifest> -- -
Finally, write your application. This section features a sample client -application that illustrates how to use the - -{@code GoogleCloudMessaging} API. The sample consists of a main activity -({@code DemoActivity}), a {@link android.support.v4.content.WakefulBroadcastReceiver} -({@code GcmBroadcastReceiver}), and an {@link android.app.IntentService} -({@code GcmIntentService}). You can find the complete source code for this sample at the -open source site.
- -Note the following:
- -As described in -Setup Google Play Services SDK, apps that rely on the Play Services SDK -should always check the device for a compatible Google Play services APK before -accessing Google Play services features. In the sample app this check is done in -two places: in the main activity's {@code onCreate()} method, and in its -{@code onResume()} method. The check in {@code onCreate()} ensures that the app -can't be used without a successful check. The check in {@code onResume()} ensures -that if the user returns to the running app through some other means, such as -through the back button, the check is still performed. If the -device doesn't have a compatible Google Play services APK, your app can call -{@code GooglePlayServicesUtil.getErrorDialog()} to allow users to download the -APK from the Google Play Store or enable it in the device's system settings. -For example:
- -private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 9000; -... -@Override -public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - - setContentView(R.layout.main); - mDisplay = (TextView) findViewById(R.id.display); - - context = getApplicationContext(); - - // Check device for Play Services APK. - if (checkPlayServices()) { - // If this check succeeds, proceed with normal processing. - // Otherwise, prompt user to get valid Play Services APK. - ... - } -} - -// You need to do the Play Services APK check here too. -@Override -protected void onResume() { - super.onResume(); - checkPlayServices(); -} - -/** - * Check the device to make sure it has the Google Play Services APK. If - * it doesn't, display a dialog that allows users to download the APK from - * the Google Play Store or enable it in the device's system settings. - */ -private boolean checkPlayServices() { - int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this); - if (resultCode != ConnectionResult.SUCCESS) { - if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) { - GooglePlayServicesUtil.getErrorDialog(resultCode, this, - PLAY_SERVICES_RESOLUTION_REQUEST).show(); - } else { - Log.i(TAG, "This device is not supported."); - finish(); - } - return false; - } - return true; -}- -
An Android application needs to register with GCM servers before it can receive -messages. When an app registers, it receives a registration ID, which it can then -store for future use (note that registration IDs must be kept secret). In the -following snippet the {@code onCreate()} method in the sample app's -main activity checks to see if the app is already registered with GCM and with -the server:
- -/** - * Main UI for the demo app. - */ -public class DemoActivity extends Activity { - - public static final String EXTRA_MESSAGE = "message"; - public static final String PROPERTY_REG_ID = "registration_id"; - private static final String PROPERTY_APP_VERSION = "appVersion"; - private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 9000; - - /** - * Substitute you own sender ID here. This is the project number you got - * from the API Console, as described in "Getting Started." - */ - String SENDER_ID = "Your-Sender-ID"; - - /** - * Tag used on log messages. - */ - static final String TAG = "GCMDemo"; - - TextView mDisplay; - GoogleCloudMessaging gcm; - AtomicInteger msgId = new AtomicInteger(); - SharedPreferences prefs; - Context context; - - String regid; - - @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - - setContentView(R.layout.main); - mDisplay = (TextView) findViewById(R.id.display); - - context = getApplicationContext(); - - // Check device for Play Services APK. If check succeeds, proceed with - // GCM registration. - if (checkPlayServices()) { - gcm = GoogleCloudMessaging.getInstance(this); - regid = getRegistrationId(context); - - if (regid.isEmpty()) { - registerInBackground(); - } - } else { - Log.i(TAG, "No valid Google Play Services APK found."); - } - } -... -}- -
The app calls {@code getRegistrationId()} to see whether there is an existing -registration ID stored in shared preferences:
- -/** - * Gets the current registration ID for application on GCM service. - * <p> - * If result is empty, the app needs to register. - * - * @return registration ID, or empty string if there is no existing - * registration ID. - */ -private String getRegistrationId(Context context) { - final SharedPreferences prefs = getGCMPreferences(context); - String registrationId = prefs.getString(PROPERTY_REG_ID, ""); - if (registrationId.isEmpty()) { - Log.i(TAG, "Registration not found."); - return ""; - } - // Check if app was updated; if so, it must clear the registration ID - // since the existing registration ID is not guaranteed to work with - // the new app version. - int registeredVersion = prefs.getInt(PROPERTY_APP_VERSION, Integer.MIN_VALUE); - int currentVersion = getAppVersion(context); - if (registeredVersion != currentVersion) { - Log.i(TAG, "App version changed."); - return ""; - } - return registrationId; -} -... -/** - * @return Application's {@code SharedPreferences}. - */ -private SharedPreferences getGCMPreferences(Context context) { - // This sample app persists the registration ID in shared preferences, but - // how you store the registration ID in your app is up to you. - return getSharedPreferences(DemoActivity.class.getSimpleName(), - Context.MODE_PRIVATE); -}- -
If the registration ID doesn't exist or the app was updated, -{@code getRegistrationId()} returns an empty string -to indicate that the app needs to get a new registration ID. {@code getRegistrationId()} calls -the following method to check the app version:
- -/** - * @return Application's version code from the {@code PackageManager}. - */ -private static int getAppVersion(Context context) { - try { - PackageInfo packageInfo = context.getPackageManager() - .getPackageInfo(context.getPackageName(), 0); - return packageInfo.versionCode; - } catch (NameNotFoundException e) { - // should never happen - throw new RuntimeException("Could not get package name: " + e); - } -}- - -
If there isn't a valid existing registration ID, {@code DemoActivity} calls the -following {@code registerInBackground()} method to register. Note that because the GCM -methods {@code register()} and {@code unregister()} are blocking, this has to -take place on a background thread. This sample uses {@link android.os.AsyncTask} -to accomplish this:
- --/** - * Registers the application with GCM servers asynchronously. - * <p> - * Stores the registration ID and app versionCode in the application's - * shared preferences. - */ -private void registerInBackground() { - new AsyncTask- -() { - @Override - protected String doInBackground(Void... params) { - String msg = ""; - try { - if (gcm == null) { - gcm = GoogleCloudMessaging.getInstance(context); - } - regid = gcm.register(SENDER_ID); - msg = "Device registered, registration ID=" + regid; - - // You should send the registration ID to your server over HTTP, - // so it can use GCM/HTTP or CCS to send messages to your app. - // The request to your server should be authenticated if your app - // is using accounts. - sendRegistrationIdToBackend(); - - // For this demo: we don't need to send it because the device - // will send upstream messages to a server that echo back the - // message using the 'from' address in the message. - - // Persist the registration ID - no need to register again. - storeRegistrationId(context, regid); - } catch (IOException ex) { - msg = "Error :" + ex.getMessage(); - // If there is an error, don't just keep trying to register. - // Require the user to click a button again, or perform - // exponential back-off. - } - return msg; - } - - @Override - protected void onPostExecute(String msg) { - mDisplay.append(msg + "\n"); - } - }.execute(null, null, null); - ... -}
Once you've received your registration ID, send it to your server:
--/** - * Sends the registration ID to your server over HTTP, so it can use GCM/HTTP - * or CCS to send messages to your app. Not needed for this demo since the - * device sends upstream messages to a server that echoes back the message - * using the 'from' address in the message. - */ -private void sendRegistrationIdToBackend() { - // Your implementation here. -}- -
After registering, the app calls {@code storeRegistrationId()} to store the -registration ID in shared preferences for future use. This is just one way of -persisting a registration ID. You might choose to use a different approach in -your app:
- -/** - * Stores the registration ID and app versionCode in the application's - * {@code SharedPreferences}. - * - * @param context application's context. - * @param regId registration ID - */ -private void storeRegistrationId(Context context, String regId) { - final SharedPreferences prefs = getGCMPreferences(context); - int appVersion = getAppVersion(context); - Log.i(TAG, "Saving regId on app version " + appVersion); - SharedPreferences.Editor editor = prefs.edit(); - editor.putString(PROPERTY_REG_ID, regId); - editor.putInt(PROPERTY_APP_VERSION, appVersion); - editor.commit(); -}- -
As stated above, an Android app must register with GCM servers and get a registration ID -before it can receive messages. A given registration ID is not guaranteed to last indefinitely, -so the first thing your app should always do is check to make sure it has a valid -registration ID (as shown in the code snippets above).
- -In addition to confirming that it has a valid registration ID, your app should be prepared to handle -the registration error {@code TOO_MANY_REGISTRATIONS}. This error indicates that the device -has too many apps registered with GCM. The error only occurs in cases where there are -extreme numbers of apps, so it should not affect the average user. The remedy is to prompt -the user to delete some of the other client apps from the device to make -room for the new one.
- -As described above in Step 2, the app includes a
-{@link android.support.v4.content.WakefulBroadcastReceiver} for the com.google.android.c2dm.intent.RECEIVE
-intent. A broadcast receiver is the mechanism GCM uses to deliver messages.
A {@link android.support.v4.content.WakefulBroadcastReceiver} is a special type of -broadcast receiver that takes care of -creating and managing a - -partial wake lock for your app. -It passes off the work of processing the GCM message to a -{@link android.app.Service} (typically an -{@link android.app.IntentService}), while ensuring that the device does not -go back to sleep in the transition. If you don't hold a wake lock while transitioning -the work to a service, you are effectively allowing the device to go back to sleep before -the work completes. The net result is that the app might not finish processing -the GCM message until some arbitrary point in the future, which is not what you want.
- -Note: Using {@link android.support.v4.content.WakefulBroadcastReceiver} -is not a requirement. If you have a relatively simple app that doesn't require -a service, you can intercept the GCM message in a regular {@link android.content.BroadcastReceiver} -and do your processing there. Once you get the intent that GCM passes into -your broadcast receiver's {@code onReceive()} method, what you do with it -is up to you.
- -This snippet starts {@code GcmIntentService} with the method -{@link android.support.v4.content.WakefulBroadcastReceiver#startWakefulService startWakefulService()}. -This method is comparable to {@link android.content.Context#startService startService()}, except that -the {@link android.support.v4.content.WakefulBroadcastReceiver} is holding a -wake lock when the service starts. The intent that is passed with -{@link android.support.v4.content.WakefulBroadcastReceiver#startWakefulService startWakefulService()} -holds an extra identifying the wake lock:
- - -public class GcmBroadcastReceiver extends WakefulBroadcastReceiver { - @Override - public void onReceive(Context context, Intent intent) { - // Explicitly specify that GcmIntentService will handle the intent. - ComponentName comp = new ComponentName(context.getPackageName(), - GcmIntentService.class.getName()); - // Start the service, keeping the device awake while it is launching. - startWakefulService(context, (intent.setComponent(comp))); - setResultCode(Activity.RESULT_OK); - } -}- -
The intent service shown below does the actual work of handling the GCM -message. When the service is finished, it calls -{@link android.support.v4.content.WakefulBroadcastReceiver#completeWakefulIntent GcmBroadcastReceiver.completeWakefulIntent()} -to release the wake lock. The -{@link android.support.v4.content.WakefulBroadcastReceiver#completeWakefulIntent completeWakefulIntent()} -method has as its parameter the same intent that was -passed in from the {@link android.support.v4.content.WakefulBroadcastReceiver}. -
- -This snippet processes the GCM message based on message type, and posts the -result in a notification. But what you do with GCM messages in your app is up to -you—the possibilities are endless. For example, the message might be a ping, -telling the app to sync to a server to retrieve new content, or it might be a -chat message that you display in the UI.
- --public class GcmIntentService extends IntentService { - public static final int NOTIFICATION_ID = 1; - private NotificationManager mNotificationManager; - NotificationCompat.Builder builder; - - public GcmIntentService() { - super("GcmIntentService"); - } - - @Override - protected void onHandleIntent(Intent intent) { - Bundle extras = intent.getExtras(); - GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this); - // The getMessageType() intent parameter must be the intent you received - // in your BroadcastReceiver. - String messageType = gcm.getMessageType(intent); - - if (!extras.isEmpty()) { // has effect of unparcelling Bundle - /* - * Filter messages based on message type. Since it is likely that GCM - * will be extended in the future with new message types, just ignore - * any message types you're not interested in, or that you don't - * recognize. - */ - if (GoogleCloudMessaging. - MESSAGE_TYPE_SEND_ERROR.equals(messageType)) { - sendNotification("Send error: " + extras.toString()); - } else if (GoogleCloudMessaging. - MESSAGE_TYPE_DELETED.equals(messageType)) { - sendNotification("Deleted messages on server: " + - extras.toString()); - // If it's a regular GCM message, do some work. - } else if (GoogleCloudMessaging. - MESSAGE_TYPE_MESSAGE.equals(messageType)) { - // This loop represents the service doing some work. - for (int i=0; i<5; i++) { - Log.i(TAG, "Working... " + (i+1) - + "/5 @ " + SystemClock.elapsedRealtime()); - try { - Thread.sleep(5000); - } catch (InterruptedException e) { - } - } - Log.i(TAG, "Completed work @ " + SystemClock.elapsedRealtime()); - // Post notification of received message. - sendNotification("Received: " + extras.toString()); - Log.i(TAG, "Received: " + extras.toString()); - } - } - // Release the wake lock provided by the WakefulBroadcastReceiver. - GcmBroadcastReceiver.completeWakefulIntent(intent); - } - - // Put the message into a notification and post it. - // This is just one simple example of what you might choose to do with - // a GCM message. - private void sendNotification(String msg) { - mNotificationManager = (NotificationManager) - this.getSystemService(Context.NOTIFICATION_SERVICE); - - PendingIntent contentIntent = PendingIntent.getActivity(this, 0, - new Intent(this, DemoActivity.class), 0); - - NotificationCompat.Builder mBuilder = - new NotificationCompat.Builder(this) - .setSmallIcon(R.drawable.ic_stat_gcm) - .setContentTitle("GCM Notification") - .setStyle(new NotificationCompat.BigTextStyle() - .bigText(msg)) - .setContentText(msg); - - mBuilder.setContentIntent(contentIntent); - mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build()); - } -}- - -
When the user clicks the app's Send button, the app sends an -upstream message using the - -{@code GoogleCloudMessaging} API. In order to receive the upstream message, -your server should be connected to CCS. You can use one of the demo servers in -Implementing an XMPP-based App Server to run the sample and connect -to CCS.
- -public void onClick(final View view) { - if (view == findViewById(R.id.send)) { - new AsyncTask- -() { - @Override - protected String doInBackground(Void... params) { - String msg = ""; - try { - Bundle data = new Bundle(); - data.putString("my_message", "Hello World"); - data.putString("my_action", - "com.google.android.gcm.demo.app.ECHO_NOW"); - String id = Integer.toString(msgId.incrementAndGet()); - gcm.send(SENDER_ID + "@gcm.googleapis.com", id, data); - msg = "Sent message"; - } catch (IOException ex) { - msg = "Error :" + ex.getMessage(); - } - return msg; - } - - @Override - protected void onPostExecute(String msg) { - mDisplay.append(msg + "\n"); - } - }.execute(null, null, null); - } else if (view == findViewById(R.id.clear)) { - mDisplay.setText(""); - } -}
To run the sample:
- -To view statistics and any error messages for your GCM applications:
-You will see a page that has a list of all of your apps.
Now you are on the statistics page.
Note: Stats on the Google API Console are not -enabled for GCM. You must use the Developer Console.
- diff --git a/docs/html/google/gcm/demo.jd b/docs/html/google/gcm/demo.jd deleted file mode 100644 index 012eb9a..0000000 --- a/docs/html/google/gcm/demo.jd +++ /dev/null @@ -1,277 +0,0 @@ -page.title=GCM Demo Application -@jd:body - - - - -The information in this document has been superseded by GCM Server and GCM Client. Please use the {@code GoogleCloudMessaging} API instead of the GCM client helper library. The GCM server helper library is still valid.
- - -Note: This tutorial describes how to develop GCM-enabled apps using the helper libraries. This is just one approach. For a more comprehensive discussion of the available APIs and development paths, see Getting Started. - -
The Google Cloud Messaging (GCM) Demo demonstrates how to use the Google Cloud Messaging framework in your Android application. This tutorial walks you through setting up and running the demo.
- - -This demo consists of the following pieces:
-See the reference for the client and server helper libraries used in this demo.
- -The sections below describe how to download the demo code and helper libraries from the SDK Manager. The demo code and helper libraries are also available at the open source site. - -
For the web server:
-For the Android application:
-Before proceeding with the server and client setup, it's necessary to register a Google account with the Google API Console, enable Google Cloud Messaging in GCM, and obtain an API key from the Google API Console.
-For instructions on how to set up GCM, see Getting Started.
- - -This section describes the different options for setting up a server.
-To set up the server using a standard, servlet-compliant web server:
-This creates a gcm
directory under YOUR_SDK_ROOT/extras/google/
containing these subdirectories: gcm-client
, gcm-server
, samples/gcm-demo-client
, samples/gcm-demo-server
, and samples/gcm-demo-appengine
.
Note: If you don't see Extras > Google Cloud Messaging for Android Library in the SDK Manager, make sure you are running version 20 or higher. Be sure to restart the SDK Manager after updating it.
-samples/gcm-demo-server/WebContent/WEB-INF/classes/api.key
and replace the existing text with the API key obtained above.samples/gcm-demo-server
directory.ant war
:$ ant war - -Buildfile:build.xml - -init: - [mkdir] Created dir: build/classes - [mkdir] Created dir: dist - -compile: - [javac] Compiling 6 source files to build/classes - -war: - [war] Building war: dist/gcm-demo.war - -BUILD SUCCESSFUL -Total time: 0 seconds -- -
dist/gcm-demo.war
to your running server. For instance, if you're using Jetty, copy gcm-demo.war
to the webapps
directory of the Jetty installation.http://192.168.1.10:8080/gcm-demo/home
, where gcm-demo
is the application context and /home
is the path of the main servlet.
-
- Note: You can get the IP by running ifconfig
on Linux or MacOS, or ipconfig
on Windows.
You server is now ready.
-To set up the server using a standard App Engine for Java:
-This creates a gcm
directory under YOUR_SDK_ROOT/extras/google/
containing these subdirectories: gcm-client
, gcm-server
, samples/gcm-demo-client
, samples/gcm-demo-server
, and samples/gcm-demo-appengine
.
samples/gcm-demo-appengine/src/com/google/android/gcm/demo/server/ApiKeyInitializer.java
and replace the existing text with the API key obtained above.
- Note: The API key value set in that class will be used just once to create a persistent entity on App Engine. If you deploy the application, you can use App Engine's Datastore Viewer
to change it later.
samples/gcm-demo-appengine
directory.ant runserver
, using the -Dsdk.dir
to indicate the location of the App Engine SDK and -Dserver.host
to set your server's hostname or IP address:-$ ant -Dsdk.dir=/opt/google/appengine-java-sdk runserver -Dserver.host=192.168.1.10 -Buildfile: gcm-demo-appengine/build.xml - -init: - [mkdir] Created dir: gcm-demo-appengine/dist - -copyjars: - -compile: - -datanucleusenhance: - [enhance] DataNucleus Enhancer (version 1.1.4) : Enhancement of classes - [enhance] DataNucleus Enhancer completed with success for 0 classes. Timings : input=28 ms, enhance=0 ms, total=28 ms. Consult the log for full details - [enhance] DataNucleus Enhancer completed and no classes were enhanced. Consult the log for full details - -runserver: - [java] Jun 15, 2012 8:46:06 PM com.google.apphosting.utils.jetty.JettyLogger info - [java] INFO: Logging to JettyLogger(null) via com.google.apphosting.utils.jetty.JettyLogger - [java] Jun 15, 2012 8:46:06 PM com.google.apphosting.utils.config.AppEngineWebXmlReader readAppEngineWebXml - [java] INFO: Successfully processed gcm-demo-appengine/WebContent/WEB-INF/appengine-web.xml - [java] Jun 15, 2012 8:46:06 PM com.google.apphosting.utils.config.AbstractConfigXmlReader readConfigXml - [java] INFO: Successfully processed gcm-demo-appengine/WebContent/WEB-INF/web.xml - [java] Jun 15, 2012 8:46:09 PM com.google.android.gcm.demo.server.ApiKeyInitializer contextInitialized - [java] SEVERE: Created fake key. Please go to App Engine admin console, change its value to your API Key (the entity type is 'Settings' and its field to be changed is 'ApiKey'), then restart the server! - [java] Jun 15, 2012 8:46:09 PM com.google.appengine.tools.development.DevAppServerImpl start - [java] INFO: The server is running at http://192.168.1.10:8080/ - [java] Jun 15, 2012 8:46:09 PM com.google.appengine.tools.development.DevAppServerImpl start - [java] INFO: The admin console is running at http://192.168.1.10:8080/_ah/admin -- -
http://192.168.1.10:8080/home
, where /home
is the path of the main servlet.Note: You can get the IP by running ifconfig
on Linux or MacOS, or ipconfig
on Windows.
You server is now ready.
-To set up the device:
-This creates a gcm
directory under YOUR_SDK_ROOT/extras/google
containing these subdirectories: gcm-client
, gcm-server
, samples/gcm-demo-client
, samples/gcm-demo-server
, and samples/gcm-demo-appengine
.
samples/gcm-demo-client/src/com/google/android/gcm/demo/app/CommonUtilities.java
and set the proper values for the SENDER_ID
and SERVER_URL
constants. For example:-static final String SERVER_URL = "http://192.168.1.10:8080/gcm-demo"; -static final String SENDER_ID = "4815162342";-
Note that the SERVER_URL
is the URL for the server and the application's context (or just server, if you are using App Engine), and it does not include the forward slash (/
). Also note that SENDER_ID
is the Google API project number you obtained in the server setup steps above.
gcm-demo-client
directory.android
tool to generate the ant
build files:-$ android update project --name GCMDemo -p . --target android-16 -Updated project.properties -Updated local.properties -Updated file ./build.xml -Updated file ./proguard-project.txt --
If this command fails becase android-16
is not recognized, try a different target (as long as it is at least android-15
).
ant
to build the application's APK file:-$ ant clean debug -Buildfile: build.xml - -... - - --do-debug: -[zipalign] Running zip align on final apk... - [echo] Debug Package: bin/GCMDemo-debug.apk -[propertyfile] Creating new property file: bin/build.prop -[propertyfile] Updating property file: bin/build.prop -[propertyfile] Updating property file: bin/build.prop -[propertyfile] Updating property file: bin/build.prop - --post-build: - -debug: - -BUILD SUCCESSFUL -Total time: 3 seconds -- -
$emulator -avd my_avd -- -
This example assumes there is an AVD (Android Virtual Device) named my_avd
previously configured with Android 2.2 and Google APIs level 8. For more information on how to run an Android emulator, see Managing Virtual Devices in the Android Developers Guide.
senderId
) in particular. If the emulator is running Android 4.0.4 or later, this step is optional as GCM does not require an account from this version on.
- --$ ant installd -Buildfile: gcm-demo-client/build.xml - --set-mode-check: - --set-debug-files: - -install: - [echo] Installing gcm-demo-client/bin/GCMDemo-debug.apk onto default emulator or device... - [exec] 1719 KB/s (47158 bytes in 0.026s) - [exec] pkg: /data/local/tmp/GCMDemo-debug.apk - [exec] Success - -installd: - -BUILD SUCCESSFUL -Total time: 3 seconds --
Note: What happened? When the device received a registration callback intent from GCM, it contacted the server to register itself, using the register servlet and passing the registration ID received from GCM; the server then saved the registration ID to use it to send messages to the phone.
-And in your emulator:
- - - -Note: What happened? When you clicked the button, the web server sent a message to GCM addressed to your device (more specifically, to the registration ID returned by GCM during the registration step). The device then received the message and displayed in the main activity; it also issued a system notification so the user would be notified even if the demo application was not running.
-Google Cloud Messaging (GCM) is a free service that enables developers -to send downstream messages (from servers to GCM-enabled client apps), and -upstream messages (from the GCM-enabled client apps to servers). -This could be a lightweight message telling the client app -that there is new data to be fetched from the server (for instance, a "new email" -notification informing the app that it is out of sync with the back end), -or it could be a message containing up to 4kb of payload -data (so apps like instant messaging can consume the message directly). The GCM -service handles all aspects of queueing of messages and delivery to and from -the target client app.
- - -This table summarizes the key terms and concepts involved in GCM. It is -divided into these categories:
-Components | -|
---|---|
GCM Connection Servers | -The Google-provided servers involved in sending messages between the -3rd-party app server and the client app. | -
Client App | -A GCM-enabled client app that communicates with a 3rd-party app server. | -
3rd-party App Server | -An app server that you write as part of implementing -GCM. The 3rd-party app server sends data to a client app via -the GCM connection server. | -
Credentials | -|
Sender ID | -A project number you acquire from the API console, as described in -Getting Started. The sender -ID is used in the registration process to identify a -3rd-party app server that is permitted to send messages to the client app. | -
Sender Auth Token | -An API key that is saved on the 3rd-party app -server that gives the app server authorized access to Google services. -The API key is included in the header of POST requests. - | -
Application ID | -The client app that is registering to receive messages. How this is implemented -is platform-dependent. For example, an Android app -is identified by the package name from the manifest. -This ensures that the messages are targeted to the correct Android app. | -
Registration ID | -An ID issued by the GCM servers to the client app that allows -it to receive messages. Note that registration IDs must be kept secret. - - | -
A GCM implementation includes a Google-provided -connection server, a 3rd-party app server that interacts with the connection -server, and a GCM-enabled client app. For example, this diagram shows GCM -communicating with a client app on an Android device:
- - - - - -This is how these components interact:
-Regardless of the platform you're developing on, the first step -a client app must do is register with GCM. This section covers some of the general -best practices for registration and unregistration. See your platform-specific docs for -details on writing a GCM-enabled client app on that platform.
- -Whenever the app registers as described in -Implementing GCM Client, -it should save the registration ID for future use, pass it to the -3rd-party server to complete the registration, and keep track of -whether the server completed the registration. If the server fails -to complete the registration, the client app should retry passing the -registration ID to 3rd-party app server to complete the registration. -If this continues to fail, the client app should unregister from GCM.
- -There are also two other scenarios that require special care:
-If a bug in the app triggers multiple -registrations for the same device, it can be hard to reconcile state and you might -end up with duplicate messages.
-GCM provides a facility called "canonical registration IDs" to easily -recover from these situations. A canonical registration ID is defined to be the ID -of the last registration requested by your app. This is the ID that the -server should use when sending messages to the device.
-If later on you try to send a message using a different registration ID, GCM
-will process the request as usual, but it will include the canonical registration
-ID in the registration_id
field of the response. Make sure to replace
-the registration ID stored in your server with this canonical ID, as eventually
-the ID you're using will stop working.
When registration or unregistration fails, the app should retry the failed operation.
-In the simplest case, if your app attempts to register and GCM is not a -fundamental part of the app, the app could simply ignore the error -and try to register again the next time it starts. Otherwise, it should retry the -previous operation using exponential back-off. In exponential back-off, each time -there is a failure, it should wait twice the previous amount of time before trying -again. -
- -This section explains when you should unregister in GCM and what happens -when you do.
- -You should only need to unregister in rare cases, such as -if you want an app to stop receiving messages, or if you suspect that the registration ID has -been compromised. In general, once an app has a registration ID, you shouldn't need -to change it.
- -In particular, you should never unregister your app as a mechanism for -logout or for switching between users, for the following reasons:
- -To make sure that messages go to the intended user:
- -A client app can be automatically unregistered after it is uninstalled. -However, this process does not happen right away. What happens in -this scenario is as follows:
-NotRegistered
error message to the 3rd-party app server.Note that it might take a while for the registration ID be completely removed
-from GCM. Thus it is possible that messages sent during step 7 above gets a valid
-message ID as response, even though the message will not be delivered to the client app.
-Eventually, the registration ID will be removed and the server will get a
-NotRegistered
error, without any further action being required from
-the 3rd-party server (this scenario happens frequently while an app is
-being developed and tested).
This document tells you how to get started setting up a Google Cloud Messaging -(GCM) implementation. -Before you begin, make sure to set up -the Google Play Services SDK. You need this SDK to use the - -GCM APIs.
- -To create a Google API project:
-Once the project has been created, a page appears that displays your project ID and -project number. For example, Project Number: 670330094152.
To enable the GCM service:
-To obtain an API key:
-Note: If you need to rotate the key, click -Regenerate key. A new key will be created. If you think the key has been -compromised and you want to delete it immediately, click Delete.
-Once you've finished the tasks listed above, you're ready to start -implementing GCM. Here is an overview of the basic steps:
- -The information in this document has been superseded by GCM Server and GCM Client. Please use the {@code GoogleCloudMessaging} API instead of the GCM client helper library. The GCM server helper library is still valid.
- - -This document describes how to write an Android application and the server-side logic, using the client and server helper libraries provided by GCM.
- -The helper libraries are one option for creating an Android application that uses GCM. You can alternatively use the approach described in the GCM Architectural Overview. If you need to perform upstream messaging, you must use the GoogleCloudMessaging APIs, and GoogleCloudMessaging also provides a streamlined registration process.
- -For information on how to get started creating an Android GCM application and an example of how to use the GoogleCloudMessaging APIs, see Getting Started.
- -To perform the steps described in the following sections, you must first install the -helper libraries. Note that while using the helper libraries is recommended, it is not required. See the GCM Architectural Overview for a description of how to write apps without using the helper libraries. - -
To install the helper libraries, choose
-Extras > Google Cloud Messaging for Android Library
-from the SDK Manager. This creates a gcm
directory under
-YOUR_SDK_ROOT/extras/google/
containing these
-subdirectories: gcm-client
, gcm-server
,
-samples/gcm-demo-client
, samples/gcm-demo-server
,
-and samples/gcm-demo-appengine
.
Note: If you don't see Extras > Google Cloud Messaging for Android Library in the SDK Manager, make sure you are running version 20 or higher. Be sure to restart the SDK Manager after updating it.
- -This section describes the steps involved in writing an Android application that uses GCM.
- To write your Android application, first copy the gcm.jar
file from the SDK's gcm-client/dist
directory to your application classpath.
<uses-sdk android:minSdkVersion="8" android:targetSdkVersion="xx"/>- -
<permission android:name="my_app_package.permission.C2D_MESSAGE" android:protectionLevel="signature" /> -<uses-permission android:name="my_app_package.permission.C2D_MESSAGE" />-
This permission must be called my_app_package.permission.C2D_MESSAGE
(where my_app_package
is the package name of your app as defined by the manifest tag), otherwise it will not work.
Note: This permission is not required if you are targeting your application to 4.1 or above (i.e., minSdkVersion 16)
- -<!-- App receives GCM messages. --> -<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" /> -<!-- GCM connects to Google Services. --> -<uses-permission android:name="android.permission.INTERNET" /> -<!-- GCM requires a Google account. --> -<uses-permission android:name="android.permission.GET_ACCOUNTS" /> -<!-- Keeps the processor from sleeping when a message is received. --> -<uses-permission android:name="android.permission.WAKE_LOCK" />- -
<receiver android:name="com.google.android.gcm.GCMBroadcastReceiver" android:permission="com.google.android.c2dm.permission.SEND" > - <intent-filter> - <action android:name="com.google.android.c2dm.intent.RECEIVE" /> - <action android:name="com.google.android.c2dm.intent.REGISTRATION" /> - <category android:name="my_app_package" /> - </intent-filter> -</receiver>-
This broadcast receiver is responsible for handling the 2 intents that can be sent by GCM (com.google.android.c2dm.intent.RECEIVE
and com.google.android.c2dm.intent.REGISTRATION
) and should be defined in the manifest (rather than programmatically) so that these intents can be received even if the application is not running. By setting the com.google.android.c2dm.permission.SEND
permission, you are ensuring that only intents sent by the GCM system framework are sent to the receiver (a regular application cannot issue intents with that permission).
Notice that android:name
in the category tag must be replaced by your application's package name (and the category tag is not required for applications targeted to minSdkVersion 16 and higher).
-
<service android:name=".GCMIntentService" />- -
This intent service will be called by the GCMBroadcastReceiver
(which is provided by the GCM library), as shown in the next step. It must be a subclass of com.google.android.gcm.GCMBaseIntentService
, must contain a public constructor, and should be named my_app_package.GCMIntentService
(unless you use a subclass of GCMBroadcastReceiver
that overrides the method used to name the service).
The intent service must also define its sender ID(s). It does this as follows:
-super(senderIds)
.getSenderIds()
method.Next write the my_app_package.GCMIntentService
class, overriding the following callback methods (which are called by GCMBroadcastReceiver
):
-
onRegistered(Context context, String regId)
: Called after a registration intent is received, passes the registration ID assigned by GCM to that device/application pair as parameter. Typically, you should send the regid
to your server so it can use it to send messages to this device.onUnregistered(Context context, String regId)
: Called after the device has been unregistered from GCM. Typically, you should send the regid
to the server so it unregisters the device.onMessage(Context context, Intent intent)
: Called when your server sends a message to GCM, and GCM delivers it to the device. If the message has a payload, its contents are available as extras in the intent.onError(Context context, String errorId)
: Called when the device tries to register or unregister, but GCM returned an error. Typically, there is nothing to be done other than evaluating the error (returned by errorId) and trying to fix the problem.onRecoverableError(Context context, String errorId)
: Called when the device tries to register or unregister, but the GCM servers are unavailable. The GCM library will retry the operation using exponential backup, unless this method is overridden and returns false. This method is optional and should be overridden only if you want to display the message to the user or cancel the retry attempts.
- Note: The methods above run in the intent service's thread and hence are free to make network calls without the risk of blocking the UI thread.
- -import com.google.android.gcm.GCMRegistrar;-
In the onCreate()
method, add the following code:
GCMRegistrar.checkDevice(this); -GCMRegistrar.checkManifest(this); -final String regId = GCMRegistrar.getRegistrationId(this); -if (regId.equals("")) { - GCMRegistrar.register(this, SENDER_ID); -} else { - Log.v(TAG, "Already registered"); -}-
The checkDevice()
method verifies that the device supports GCM and throws an exception if it does not (for instance, if it is an emulator that does not contain the Google APIs). Similarly, the checkManifest()
method verifies that the application manifest contains meets all the requirements described in Writing the Android Application (this method is only necessary when you are developing the application; once the application is ready to be published, you can remove it).
Once the sanity checks are done, the device calls GCMRegsistrar.register()
to register the device, passing the SENDER_ID
you got when you signed up for GCM. But since the GCMRegistrar
singleton keeps track of the registration ID upon the arrival of registration intents, you can call GCMRegistrar.getRegistrationId()
first to check if the device is already registered.
Note: It is possible that the device was successfully registered to GCM but failed to send the registration ID to your server, in which case you should retry. See Advanced Topics for more details on how to handle this scenario.
- -To write the server-side application:
-gcm-server.jar
file from the SDK's gcm-server/dist
directory to your server classpath.com.google.android.gcm.server.Sender
helper class from the GCM library. For example:import com.google.android.gcm.server.*; - -Sender sender = new Sender(myApiKey); -Message message = new Message.Builder().build(); -MulticastResult result = sender.send(message, devices, 5);- -
The snippet above does the following: -
Sender
object using your project's API key.It's now necessary to parse the result and take the proper action in the following cases:
-NotRegistered
, it's necessary to remove that registration ID, because the application was uninstalled from the device.Here's a code snippet that handles these 2 conditions:
--if (result.getMessageId() != null) { - String canonicalRegId = result.getCanonicalRegistrationId(); - if (canonicalRegId != null) { - // same device has more than on registration ID: update database - } -} else { - String error = result.getErrorCodeName(); - if (error.equals(Constants.ERROR_NOT_REGISTERED)) { - // application has been removed from device - unregister database - } -}diff --git a/docs/html/google/gcm/http.jd b/docs/html/google/gcm/http.jd deleted file mode 100644 index e36440a..0000000 --- a/docs/html/google/gcm/http.jd +++ /dev/null @@ -1,445 +0,0 @@ -page.title=GCM HTTP Connection Server -@jd:body - -
This document describes the Google Cloud Messaging (GCM) HTTP -connection server. Connection servers -are the Google-provided servers that take messages from the 3rd-party -application server and sending them to the device.
- -Note: The content in this document -applies to -GCM with Chrome apps as well as Android.
- -See the -Server Reference for a list of all the message -parameters and which connection server(s) supports them.
- - -To send a message, the application server issues a POST request. For example:
-https://android.googleapis.com/gcm/send-
A message request is made of 2 parts: HTTP header and HTTP body.
- -The HTTP header must contain the following headers:
-Authorization
: key=YOUR_API_KEYContent-Type
: application/json
for JSON;
-application/x-www-form-urlencoded;charset=UTF-8
for plain text.
-If Content-Type
is omitted, the format
-is assumed to be plain text.
- For example: -
- -Content-Type:application/json -Authorization:key=AIzaSyB-1uEai2WiUapxCs2Q0GZYzPu7Udno5aA - -{ - "registration_ids" : ["APA91bHun4MxP5egoKMwt2KZFBaFUH-1RYqx..."], - "data" : { - ... - }, -}- - -
The HTTP body content depends on whether you're using JSON or plain text. -See -the Server Reference for a list of all the -parameters your JSON or plain text message can contain.
- -If you receive authentication errors when sending messages, check the validity -of your API key. For example, on Android, run the following command:
- -# api_key=YOUR_API_KEY - -# curl --header "Authorization: key=$api_key" \ - --header Content-Type:"application/json" \ - https://android.googleapis.com/gcm/send \ - -d "{\"registration_ids\":[\"ABC\"]}"- -
-If you receive a 401 HTTP status code, your API key is not valid. Otherwise you -should see something like this:
- --{"multicast_id":6782339717028231855,"success":0,"failure":1, -"canonical_ids":0,"results":[{"error":"InvalidRegistration"}]} -- -
-If you want to confirm the validity of a registration ID, you can do so by -replacing "ABC" with the registration ID. -
- - -This section shows you how to format a request for both JSON and plain text. See -the Server Reference for a complete -list of the fields you can include in a request.
- -Here is the smallest possible request (a message without any parameters and -just one recipient) using JSON:
- -{ "registration_ids": [ "42" ] }- -
And here the same example using plain text:
-registration_id=42- -
Here is a message with a payload and 6 recipients:
- -{ "data": { - "score": "5x1", - "time": "15:10" - }, - "registration_ids": ["4", "8", "15", "16", "23", "42"] -}-
Here is a message with all optional fields set and 6 recipients:
-{ "collapse_key": "score_update", - "time_to_live": 108, - "delay_while_idle": true, - "data": { - "score": "4x8", - "time": "15:16.2342" - }, - "registration_ids":["4", "8", "15", "16", "23", "42"] -}-
And here is the same message using plain-text format (but just 1 recipient):
- -collapse_key=score_update&time_to_live=108&delay_while_idle=1&data.score=4x8&data.time=15:16.2342®istration_id=42 -- -
Here is a message that includes a notification key and payload:
- --{ - "data": { - "message": "ciao" - }, - "notification_key":"aUniqueKey" -} -- -
For more information about notifications and how to use them, see -User Notifications.
- - -Note: If your organization has a firewall -that restricts the traffic to or -from the Internet, you need to configure it to allow connectivity with GCM in order for -your GCM client apps to receive messages. -The ports to open are: 5228, 5229, and 5230. GCM typically only uses 5228, but -it sometimes uses 5229 and 5230. GCM doesn't provide specific IPs, so you should allow -your firewall to accept outgoing connections to all IP addresses -contained in the IP blocks listed in Google's ASN of 15169.
- - - -There are two possible outcomes when trying to send a message:
-When a JSON request is successful (HTTP status code 200), the JSON object returned -contains the -Downstream HTTP message response body.
- -If the value of failure
and canonical_ids
is 0, it's
-not necessary to parse the remainder of the response. Otherwise, we recommend
-that you iterate through the results field and do the following for each object
-in that list:
message_id
is set, check for registration_id
:
- registration_id
is set, replace the original ID with
-the new value (canonical ID) in your server database. Note that the original ID
-is not part of the result, so you need to obtain it from the list of
-code>registration_ids passed in the request (using the same index).error
:
- Unavailable
, you could retry to send it in another
-request.NotRegistered
, you should remove the registration
-ID from your server database because the application was uninstalled from the
-device, or the client app isn't configured to receive
-messages.When a plain-text request is successful (HTTP status code 200), the response
-body contains 1 or 2 lines in the form of key/value pairs.
-The first line is always available and its content is either id=ID of
-sent message
or Error=GCM error code
. The second
-line, if available,
-has the format of registration_id=canonical ID
. The second
-line is optional, and it can only be sent if the first line is not an error. We
-recommend handling the plain-text response in a similar way as handling the
-JSON response:
id
, check second line:
- registration_id
, gets its value
-and replace the registration IDs in your server database.Error
:
- NotRegistered
, remove the registration ID from
-your server database.Unavailable
as the
-error code, they would have returned a 500 HTTP status instead).This section shows a few examples of responses indicating messages that were -processed successfully. See Request Format for -the requests these responses are based on.
-Here is a simple case of a JSON message successfully sent to one recipient -without canonical IDs in the response:
-{ "multicast_id": 108, - "success": 1, - "failure": 0, - "canonical_ids": 0, - "results": [ - { "message_id": "1:08" } - ] -}- -
Or if the request was in plain-text format:
-id=1:08 -- -
Here are JSON results for 6 recipients (IDs 4, 8, 15, 16, 23, and 42 respectively) -with 3 messages successfully processed, 1 canonical registration ID returned, -and 3 errors:
-{ "multicast_id": 216, - "success": 3, - "failure": 3, - "canonical_ids": 1, - "results": [ - { "message_id": "1:0408" }, - { "error": "Unavailable" }, - { "error": "InvalidRegistration" }, - { "message_id": "1:1516" }, - { "message_id": "1:2342", "registration_id": "32" }, - { "error": "NotRegistered"} - ] -} --
In this example:
-Or if just the 4th message above was sent using plain-text format:
-Error=InvalidRegistration --
If the 5th message above was also sent using plain-text format:
-id=1:2342 -registration_id=32 -- - -
This section gives examples of implementing an app server that works with the -GCM HTTP connection server. Note that a full GCM implementation requires a -client-side implementation, in addition to the server. This example is based on Android. - - -
Requirements
-For the web server:
-For the Android application:
-Before proceeding with the server and client setup, it's necessary to register -a Google account with the Google API Console, enable Google Cloud Messaging in GCM, -and obtain an API key from the -Google API Console.
-For instructions on how to set up GCM, see Getting Started.
- - -This section describes the different options for setting up an HTTP server.
- -To set up the server using a standard, servlet-compliant web server:
-gcm-server
,
-samples/gcm-demo-server
, and samples/gcm-demo-appengine
.
-
-
- samples/gcm-demo-server/WebContent/WEB-INF/classes/api.key
and replace the existing text with the API key obtained above.samples/gcm-demo-server
directory.ant war
:$ ant war - -Buildfile:build.xml - -init: - [mkdir] Created dir: build/classes - [mkdir] Created dir: dist - -compile: - [javac] Compiling 6 source files to build/classes - -war: - [war] Building war: dist/gcm-demo.war - -BUILD SUCCESSFUL -Total time: 0 seconds -- -
dist/gcm-demo.war
to your running server. For instance, if you're using Jetty, copy gcm-demo.war
to the webapps
directory of the Jetty installation.http://192.168.1.10:8080/gcm-demo/home
, where gcm-demo
is the application context and /home
is the path of the main servlet.
-
- Note: You can get the IP by running ifconfig
on Linux or MacOS, or ipconfig
on Windows.
You server is now ready.
- -To set up the server using a standard App Engine for Java:
-samples/gcm-demo-appengine/src/com/google/android/gcm/demo/server/ApiKeyInitializer.java
-and replace the existing text with the API key obtained above.
-
- Note: The API key value set in that class will
-be used just once to create a persistent entity on App Engine. If you deploy
-the application, you can use App Engine's Datastore Viewer
to change
-it later.
samples/gcm-demo-appengine
directory.ant runserver
,
-using the -Dsdk.dir
to indicate the location of the App Engine SDK
-and -Dserver.host
to set your server's hostname or IP address:-$ ant -Dsdk.dir=/opt/google/appengine-java-sdk runserver -Dserver.host=192.168.1.10 -Buildfile: gcm-demo-appengine/build.xml - -init: - [mkdir] Created dir: gcm-demo-appengine/dist - -copyjars: - -compile: - -datanucleusenhance: - [enhance] DataNucleus Enhancer (version 1.1.4) : Enhancement of classes - [enhance] DataNucleus Enhancer completed with success for 0 classes. Timings : input=28 ms, enhance=0 ms, total=28 ms. Consult the log for full details - [enhance] DataNucleus Enhancer completed and no classes were enhanced. Consult the log for full details - -runserver: - [java] Jun 15, 2012 8:46:06 PM com.google.apphosting.utils.jetty.JettyLogger info - [java] INFO: Logging to JettyLogger(null) via com.google.apphosting.utils.jetty.JettyLogger - [java] Jun 15, 2012 8:46:06 PM com.google.apphosting.utils.config.AppEngineWebXmlReader readAppEngineWebXml - [java] INFO: Successfully processed gcm-demo-appengine/WebContent/WEB-INF/appengine-web.xml - [java] Jun 15, 2012 8:46:06 PM com.google.apphosting.utils.config.AbstractConfigXmlReader readConfigXml - [java] INFO: Successfully processed gcm-demo-appengine/WebContent/WEB-INF/web.xml - [java] Jun 15, 2012 8:46:09 PM com.google.android.gcm.demo.server.ApiKeyInitializer contextInitialized - [java] SEVERE: Created fake key. Please go to App Engine admin console, change its value to your API Key (the entity type is 'Settings' and its field to be changed is 'ApiKey'), then restart the server! - [java] Jun 15, 2012 8:46:09 PM com.google.appengine.tools.development.DevAppServerImpl start - [java] INFO: The server is running at http://192.168.1.10:8080/ - [java] Jun 15, 2012 8:46:09 PM com.google.appengine.tools.development.DevAppServerImpl start - [java] INFO: The admin console is running at http://192.168.1.10:8080/_ah/admin -- -
http://192.168.1.10:8080/home
, where /home
-is the path of the main servlet.Note: You can get the IP by running ifconfig
-on Linux or MacOS, or ipconfig
on Windows.
You server is now ready.
diff --git a/docs/html/google/gcm/index.jd b/docs/html/google/gcm/index.jd deleted file mode 100644 index af5d741..0000000 --- a/docs/html/google/gcm/index.jd +++ /dev/null @@ -1,70 +0,0 @@ -page.title=Google Cloud Messaging for Android -page.tags=gcm -header.hide=1 -@jd:body - - - - -This could be a lightweight -message telling your app there is new data to be fetched from the -server (for instance, a movie uploaded by a friend), or it could be a message containing -up to 4kb of payload data (so apps like instant messaging can consume the message directly). -GCM Architectural Overview.
- -A send-to-sync (collapsible) message is often a "tickle" that tells a mobile - application to sync data from the server. For example, suppose you have an email - application. When a user receives new email on the server, the server pings the mobile - application with a "New mail" message. This tells the application to sync to the server - to pick up the new email. - Learn more »
- -Unlike a send-to-sync message, every "message with payload" (non-collapsible message) - is delivered. The payload the message contains can be up to 4kb. - Learn more »
-You can use upstream messaging to get receipt notifications, confirming that a given - message was sent to a device. Your 3rd-party app server receives the receipt notification - from CCS once the message has been sent to the device. - Learn more »
- - -Get started with a tutorial that walks you through creating a GCM app. - Learn more »
-With user notifications, 3rd-party app servers can send a single message to -multiple instance of an app running on devices owned by a single user. This feature -is called user notifications. User notifications make it possible for every -app instance that a user owns to reflect the latest messaging state. For example:
- -The way this works is that during registration, the 3rd-party server requests -a {@code notification_key}. The {@code notification_key} maps a particular user -to all of the user's associated registration IDs (a regID represents a particular -Android application running on a particular device). Then instead of sending one -message to one regID at a time, the 3rd-party server can send a message to to the -{@code notification_key}, which then sends the message to all of the user's regIDs.
- -Note: A notification dismissal message is like any -other upstream message, meaning that it will be delivered to the other devices that -belong to the specified {@code notification_key}. You should design your app to -handle cases where the app receives a dismissal message, but has not yet displayed -the notification that is being dismissed. You can solve this by caching the dismissal -and then reconciling it with the corresponding notification. -
- -You can use this feature with either the XMPP (CCS) or -HTTP connection server.
- -You can generate notification keys in two different ways: on the server, and on -the client, if the user has a Google account. All of the associated registration IDs -can be mapped to a single user.
- -The examples below show you how to perform generate/add/remove operations, -and how to send upstream messages. For generate/add/remove operations, the -message body is JSON.
- -To generate a notification key on the server, you create a new
-notification_key
and map it to a
-notification_key_name
.
This example shows how to create a new notification_key
for a
-notification_key_name
called appUser-Chris
.
-The {@code notification_key_name} is a name or identifier (it can be a username for
-a 3rd-party app) that is unique to a given user. It is used by third parties to
-group together registration IDs for a single user. Note that notification_key_name
-and notification_key
are unique to a group of registration IDs. It is also
-important that notification_key_name
be uniquely named per app in case
-you have multiple apps for the same project ID. This ensures that notifications
-only go to the intended target app.
A create operation returns a token (notification_key
). Third parties
-must save this token (as well as its mapping to the notification_key_name
)
-to use in subsequent operations:
request: -{ - "operation": "create", - "notification_key_name": "appUser-Chris", - "registration_ids": ["4", "8", "15", "16", "23", "42"] -}- -
To send a message in cases where your notification key is generated on the server,
-the application server issues a POST request to
-https://android.googleapis.com/gcm/notification
.
Here is the HTTP request header you should use for all server side create/add/remove operations:
- -content-type: "application/json" -Header : "project_id": <projectID> -Header: "Authorization", "key=API_KEY" -- - -
Generating a notification key on the client is useful for cases where a server is unavailable. -To generate a notification key on the client, the device must have at least one -Google account. Note that the process for generating a notification key on the client is significantly -different from the server process described above.
- -To generate a notification key on the client:
- -Once you've followed the above steps and gotten a client ID from Google Developers Console, - you're ready to add this feature to your app. First check the device for the presence of a Google -account. For example:
- -// This snippet takes the simple approach of using the first returned Google account, -// but you can pick any Google account on the device. -public String getAccount() { - Account[] accounts = AccountManager.get(getActivity()). - getAccountsByType("com.google"); - if (accounts.length == 0) { - return null; - } - return accounts[0].name; -}- -
Next, get an authentication token ({@code id_token}) by using the GoogleAuthUtil
-class. For example:
String accountName = getAccount(); - -// Initialize the scope using the client ID you got from the Console. -final String scope = "audience:server:client_id:" - + "1262xxx48712-9qs6n32447mcj9dirtnkyrejt82saa52.apps.googleusercontent.com"; -String id_token = null; -try { - id_token = GoogleAuthUtil.getToken(context, accountName, scope); -} catch (Exception e) { - log("exception while getting id_token: " + e); -} -...- -
Now use id_token
to authenticate your request.
-This add operation returns a {@code notification_key}.
-Third parties must save this {@code notification_key} (as well as its mapping to the
-notification_key_name
)
-to use in subsequent operations. Note that a client request only takes a single regID.
-The only operations supported on the client side are add/remove.
request: -{ - "operation": "add", - "notification_key_name": "appUser-Chris", - "registration_ids": ["4"] - "id_token": "id_token" -}- -
To send a message in cases where your notification key is generated on the client,
-the application server issues a POST request to
-https://android.googleapis.com/gcm/googlenotification
.
Here is the HTTP request header you should use for all add/remove operations. The -client side doesn't support the create operation; -the add operation has the effect of creating the notification key if it doesn't already -exist:
- -content-type: "application/json" -Header : "project_id": <projectID> -- -
Note that the authentication token is passed in the JSON body as shown above, not the header. -This is different from the server case.
- - -This example shows how to add registration IDs for a given notification key. -The maximum number of members allowed for a {@code notification_key} is 20.
- -Note that the notification_key_name
is not strictly required for
-adding/removing regIDs. But including it protects you against accidentally using
-the incorrect notification_key
.
request: -{ - "operation": "add", - "notification_key_name": "appUser-Chris", - "notification_key": "aUniqueKey" - "registration_ids": ["4", "8", "15", "16", "23", "42"] -}- -
This example shows how to remove registration IDs for a given notification key:
-request: -{ - "operation": "remove", - "notification_key_name": "appUser-Chris", - "notification_key": "aUniqueKey" - "registration_ids": ["4", "8", "15", "16", "23", "42"] -}- -
To send an upstream (device-to-cloud) message, you must use the - -{@code GoogleCloudMessaging} API. Specifying a {@code notification_key} as the target -for an upstream message allows a user on one device to send a message to other -devices in the notification group—for example, to dismiss a notification. -Here is an example that shows targeting a {@code notification_key}:
- -GoogleCloudMessaging gcm = GoogleCloudMessaging.get(context); -String to = NOTIFICATION_KEY; -AtomicInteger msgId = new AtomicInteger(); -String id = Integer.toString(msgId.incrementAndGet()); -Bundle data = new Bundle(); -data.putString("hello", "world"); - -gcm.send(to, id, data); -- -
This call generates the necessary XMPP stanza for sending the message. The -Bundle data consists of a key-value pair.
- -For a complete example, see Implementing GCM Client. - -
This section shows examples of the responses that can be returned for -notification key operations.
- -When you make a request to create a {@code notification_key} or to add/remove its
-regIDs, a successful response always returns the notification_key
.
-Use the returned {@code notification_key} for sending messages:
HTTP status: 200 -{ - "notification_key": "aUniqueKey", // to be used for sending -}- - -
For a send operation that has a {@code notification_key} as its target, the -possible responses are success, partial success, and failure.
- -Here is an example of "success"—the {@code notification_key} has 2 regIDs -associated with it, and the message was successfully sent to both of them:
- -{ - "success": 2, - "failure": 0 -}- -
Here is an example of "partial success"—the {@code notification_key} has -3 regIDs associated with it. The message was successfully send to 1 of the regIDs, -but not to the other 2. The response message lists the regIDs that failed to -receive the message:
- -{ - "success":1, - "failure":2, - "failed_registration_ids":[ - "regId1", - "regId2" - ] -}- -
In the case of failure, the response has HTTP code 503 and no JSON. When a message -fails to be delivered to one or more of the regIDs associated with a {@code notification_key}, -the 3rd-party server should retry.
diff --git a/docs/html/google/gcm/server-ref.jd b/docs/html/google/gcm/server-ref.jd deleted file mode 100644 index 2a41e58..0000000 --- a/docs/html/google/gcm/server-ref.jd +++ /dev/null @@ -1,764 +0,0 @@ -page.title=Server Reference -@jd:body - -This document provides a reference for the syntax used to pass -messages back and forth in GCM. These messages fall into -the following broad categories:
- -The following sections describe the basic requirements for -sending messages.
- -This is the message that a 3rd-party app server sends to a client app. -
-A downstream message includes the following components:
-The syntax for each of these components is described in the tables below.
- -This section gives the syntax for sending a downstream messages. For JSON, -these messages can be either HTTP or XMPP. For plain text, these messages can only be HTTP.
- -The following table lists the targets, options, and payload for HTTP or XMPP JSON messages.
- -Parameter | -Protocol | -Usage | -Description | -
---|---|---|---|
Targets | -|||
to |
- XMPP | -Required, string | -This parameter specifies the recipient of a message. -The value must be a registration ID or notification key. -This parameter is used in XMPP in place of {@code registration_ids} or {@code notification_key} in HTTP. |
-
registration_ids |
- HTTP | -Required if {@code notification_key} not present, string array | -This parameter specifies the list of devices (registration IDs) -receiving the message. It must contain at least 1 and at most 1000 registration IDs. -Multicast messages (sending to more than 1 registration IDs) are allowed using HTTP JSON format only. -This parameter or {@code notification_key} is used in HTTP in place of {@code to} in XMPP. |
-
notification_key |
- HTTP | -Required if {@code registration_ids} not present, string | -This parameter specifies the mapping of a single user to -multiple registration IDs associated with that user. -This allows a 3rd-party app server to send a single message to multiple app instances -(typically on multiple devices) owned by a single user. -A 3rd-party app server can use {@code notification_key} as the target for a -message instead of an individual registration ID (or array of registration IDs). -The maximum number of members allowed for a {@code notification_key} is 20. -This parameter or {@code registration_ids} is used in HTTP in place of {@code to} in XMPP. -See User Notifications for details. |
-
Options | -|||
message_id |
- XMPP | -Required, string | -This parameter uniquely identifies a message in an XMPP connection. |
-
collapse_key |
- HTTP, XMPP | -Optional, string | -This parameters identifies a group of messages (e.g., with -{@code collapse_key: "Updates Available"}) that can be collapsed, so that only the -last message gets sent when delivery can be resumed. This is intended to avoid sending too -many of the same messages when the device comes back online or becomes active (see {@code delay_while_idle}). -Note that there is no guarantee of the order in which messages get sent. -Messages with collapse key are also called -send-to-sync messages messages. - -Note: A maximum of 4 different collapse keys is allowed at any given time. This means a -GCM connection server can simultaneously store 4 different send-to-sync messages per client app. If you -exceed this number, there is no guarantee which 4 collapse keys the GCM connection server will keep. |
-
delay_while_idle |
- HTTP, XMPP | -Optional, JSON boolean | -When this parameter is set to {@code true}, it indicates that the message should not be
-sent until the device becomes active.
- The default value is {@code false}. |
-
time_to_live |
- HTTP, XMPP | -Optional, JSON number | -This parameter specifies how long (in seconds) the message should be kept in GCM storage -if the device is offline. The maximum time to live supported is 4 weeks. -The default value is 4 weeks. |
-
delivery_receipt_
- |
- XMPP | -Optional, JSON boolean | -This parameter lets 3rd-party app server request confirmation of message delivery. -When this parameter is set to {@code true}, CCS sends a delivery receipt -when the device confirms that it received the message. -The default value is {@code false}. |
-
restricted_package_
- |
- HTTP | -Optional, string | -This parameter specifies the package name of the application where the -registration IDs must match in order to receive the message. | -
dry_run |
- HTTP | -Optional, JSON boolean | -This parameter, when set to {@code true}, allows developers to test a -request without actually sending a message. -The default value is {@code false}. |
-
Payload | -|||
data |
- HTTP, XMPP | -Optional, JSON object | -This parameter specifies the key-value pairs of the message's payload. There is -no limit on the number of key-value pairs, but there is a total message size limit of 4kb. -For instance, in Android, The key should not be a reserved word ({@code from} or any word starting with -{@code google}). It is also not recommended to use words defined in this table -(such as {@code collapse_key}) because that could yield unpredictable outcomes. -Values in string types are recommended. You have to convert values in objects -or other non-string data types (e.g., integers or booleans) to string. |
-
The following table lists the syntax for targets, options, and payload in plain -text downstream HTTP messages.
- - - -Parameter | -Usage | -Description | -
---|---|---|
Targets | -||
registration _id |
- Required, string | -This parameter specifies the client apps (registration ID) receiving the message. -Multicast messaging (sending to more than one registration ID) is allowed using HTTP JSON format only. |
-
Options | -||
collapse_key |
- Optional, string | -See table 1 for details. | -
delay_while_idle |
- Optional, boolean or number | -See table 1 for details. | -
time_to_live |
- Optional, number | -See table 1 for details. | -
restricted_package_name |
- Optional, string | -See table 1 for details. | -
dry_run |
- Optional, boolean | -See table 1 for details. | -
Payload | -||
data.<key> |
- Optional, string | -This parameter specifies the key-value pairs of the message's payload. -There is no limit on the number of key-value parameters, -but there is a total message size limit of 4kb. -For instance, in Android, The key should not be a reserved word ({@code from} or any word starting with -{@code google}). It is also not recommended to use words defined in this table -(such as {@code collapse_key}) because that could yield unpredictable outcomes. |
-
This section describes the syntax of a response to a downstream message. A client -app or the GCM Connection Server sends the response to 3rd-party app server upon processing -the message request.
- -The 3rd-party app server should look at both the message response header and the body -to interpret the message response sent from the GCM Connection Server. The following table -describes the possible responses.
-- -
-Response | -Description | -
---|---|
200 | -Message was processed successfully. The response body will contain more -details about the message status, but its format will depend whether the request -was JSON or plain text. See table 4 -for more details. | -
400 | -Only applies for JSON requests. -Indicates that the request could not be parsed as JSON, or it contained invalid -fields (for instance, passing a string where a number was expected). The exact -failure reason is described in the response and the problem should be addressed -before the request can be retried. | -
401 | -There was an error authenticating the sender account. -Troubleshoot | -
5xx | -Errors in the 500-599 range (such as 500 or 503) indicate that there was
-an internal error in the GCM server while trying to process the request, or that
-the server is temporarily unavailable (for example, because of timeouts). Sender
-must retry later, honoring any Retry-After header included in the
-response. Application servers must implement exponential back-off.
-Troubleshoot |
-
The following table lists the fields in a downstream message response body -(JSON).
- - - -Parameter | -Usage | -Description | -
---|---|---|
multicast_id |
- Required, number | -Unique ID (number) identifying the multicast message. | -
success |
- Required, number | -Number of messages that were processed without an error. | -
failure |
- Required, number | -Number of messages that could not be processed. | -
canonical_ids |
- Required, number | -Number of results that contain a canonical registration ID. See the -Overview for more discussion of this topic. | -
results |
- Optional, array object | -Array of objects representing the status of the messages processed. The
-objects are listed in the same order as the request (i.e., for each registration
-ID in the request, its result is listed in the same index in the response). -
|
-
Parameter | -Usage | -Description | -
---|---|---|
id |
- Required, string | -This parameter specifies the unique message ID that GCM server processed successfully. | -
registration_id |
- Optional, string | -This parameter specifies the canonical registration ID for the client app that the message was -processed and sent to. Sender should replace the registration ID with this value on future requests, -otherwise, the messages might be rejected. | -
Parameter | -Usage | -Description | -
---|---|---|
{@code Error} | -Required, string | -This parameter specifies the error value while processing the message for the recipient. -See table 11 for details. | -
The following table lists the fields that appear in a downstream XMPP message response.
- - -Parameter | -Usage | -Description | -
---|---|---|
from |
- Required, string | -This parameter specifies who sent this response. -The value is the registration ID of the client app. |
-
message_id |
- Required, string | -This parameter uniquely identifies a message in an XMPP connection. -The value is a string that uniquely identifies the associated message. | -
message_type |
- Required, string | -This parameter specifies an 'ack' or 'nack' message from XMPP (CCS) -to the 3rd-party app server. -If the value is set to {@code nack}, the 3rd-party app server should look at -{@code error} and {@code error_description} to get failure information. |
-
error |
- Optional, string | -This parameter specifies an error related to the downstream message. It is set when the -{@code message_type} is {@code nack}. See table 6 for details. | -
error_description |
- Optional, string | -This parameter provides descriptive information for the error. It is set -when the {@code message_type} is {@code nack}. | -
An upstream message is a message the client app sends to the 3rd-party app server. -Currently only CCS (XMPP) supports upstream messaging.
- -The following table describes the fields that appear in an upstream XMPP message. - -
-Parameter | -Usage | -Description | -
---|---|---|
from |
- Required, string | -This parameter specifies who sent the message. -The value is the registration ID of the client app. |
-
category |
- Required, string | -This parameter specifies the application package name of the client app that sent the message. | -
message_id |
- Required, string | -This parameter specifies the unique ID of the message. | -
data |
- Optional, string | -This parameter specifies the key-value pairs of the message's payload. | -
The following table describes the response that 3rd-party app server is expected to send to -XMPP (CCS) in response to an -upstream message it (the app server) received.
- - -Parameter | -Usage | -Description | -
---|---|---|
to |
- Required, string | -This parameter specifies the recipient of a response message. -The value must be a registration ID of the client app that sent the upstream message. |
-
message_id |
- Required, string | -This parameter specifies which message the response is intended for. The value must be -the {@code message_id} value from the corresponding upstream message. | -
message_type |
- Required, string | -This parameter specifies an {@code ack} message from a 3rd-party app server to CCS. | -
This is a message sent from XMPP (CCS) to a 3rd-party app server. Here are the primary types -of messages that XMPP (CCS) sends to the 3rd-party app server:
-The following table describes the fields included in the messages CCS -sends to a 3rd-party app server.
- - -Parameter | -Usage | -Description | -
---|---|---|
Common Field | -||
message_type |
- Required, string | -This parameter specifies the type of the CCS message: either delivery receipt or control. -When it is set to {@code receipt}, the message includes {@code from}, {@code message_id}, - {@code category} and {@code data} fields to provide additional information. -When it is set to {@code control}, the message includes {@code control_type} to indicate the -type of control message. |
-
Delivery receipt-specific | -||
from |
- Required, string | -This parameter is set to {@code gcm.googleapis.com}, indicating that the -message is sent from CCS. | -
message_id |
- Required, string | -This parameter specifies the original message ID that the receipt is intended for, -prefixed with {@code dr2:} to indicate that the message is a delivery receipt. A 3rd-party app -server must send an {@code ack} message with this message ID to acknowledge that it -received this delivery receipt. See table 9 for the 'ack' message format. | -
category |
- Optional, string | -This parameter specifies the application package name of the client app that -receives the message that this delivery receipt is reporting. This is available when -{@code message_type} is {@code receipt}. | -
data |
- Optional, string | -This parameter specifies the key-value pairs for the delivery receipt message. This is available
-when the {@code message_type} is {@code receipt}.
-
|
-
Control-specific | -||
control_type |
- Optional, string | -This parameter specifies the type of control message sent from CCS. -Currently, only {@code CONNECTION_DRAINING} is supported. XMPP (CCS) sends this control message -before it closes a connection to perform load balancing. As the connection drains, no more messages -are allowed to be sent to the connection, but existing messages in the pipeline will -continue to be processed. |
-
The following table lists the error response codes for downstream messages (HTTP and XMPP).
- - -Error | -HTTP Code | -XMPP Code | -Recommended Action | -
---|---|---|---|
Missing Registration ID | -200 + error:MissingRegistration | -INVALID_JSON |
- Check that the request contains a registration ID (either in the -{@code registration_id} in a plain text message, or in the {@code registration_ids} in JSON). | -
Invalid Registration ID | -200 + error:InvalidRegistration | -BAD_REGISTRATION |
- Check the format of the registration ID you pass to the server. Make sure it -matches the registration ID the client app receives from registering with GCM. Do not -truncate or add additional characters. | -
Unregistered Device | -200 + error:NotRegistered | -DEVICE_UNREGISTERED |
- An existing registration ID may cease to be valid in a number of scenarios, including: -
|
-
Invalid Package Name | -200 + error:InvalidPackageName | -- | Make sure the message was addressed to a registration ID whose package name -matches the value passed in the request. | -
Authentication Error | -401 | -- | The sender account used to send a message couldn't be authenticated. Possible causes are: -
|
-
Mismatched Sender | -200 + error:MismatchSenderId | -BAD_REGISTRATION |
- A registration ID is tied to a certain group of senders. When a client app registers -for GCM, it must specify which senders are allowed to send messages. You should use one -of those sender IDs when sending messages to the client app. If you switch to a different -sender, the existing registration IDs won't work. | -
Invalid JSON | -400 | -INVALID_JSON |
- Check that the JSON message is properly formatted and contains valid fields -(for instance, making sure the right data type is passed in). | -
Message Too Big | -200 + error:MessageTooBig | -INVALID_JSON |
- Check that the total size of the payload data included in a message does -not exceed 4096 bytes. This includes both the the keys and the values. | -
Invalid Data Key | -200 + error:
- -InvalidDataKey |
- INVALID_JSON |
- Check that the payload data does not contain a key (such as {@code from} or any value -prefixed by {@code google}) that is used internally by GCM. Note that some words (such as {@code collapse_key}) -are also used by GCM but are allowed in the payload, in which case the payload value -will be overridden by the GCM value. | -
Invalid Time to Live | -200 + error:InvalidTtl | -INVALID_JSON |
- Check that the value used in {@code time_to_live} is an integer representing a -duration in seconds between 0 and 2,419,200 (4 weeks). | -
Bad ACK message | -N/A | -BAD_ACK |
- Check that the 'ack' message is properly formatted before retrying. See -table 9 for details. | -
Timeout | -5xx or 200 + error:Unavailable | -SERVICE_UNAVAILABLE |
- The server couldn't process the request in time. Retry the same request, but you must:
Senders that cause problems risk being blacklisted. |
-
Internal Server Error | -500 or 200 + error:InternalServerError | -INTERNAL_SERVER_
- |
- The server encountered an error while trying to process the request. You could retry -the same request following the requirements listed in "Timeout" (see row above). If the error persists, please -report the problem in the {@code android-gcm group}. | -
Device Message Rate Exceeded | -200 + error:
- DeviceMessageRate - -Exceeded |
- DEVICE_MESSAGE_RATE |
- The rate of messages to a particular device is too high. Reduce the -number of messages sent to this device and do not immediately retry sending to this device. | -
Connection Draining | -N/A | -CONNECTION_DRAINING |
- The message couldn't be processed because the connection is draining. This happens because -periodically, XMPP (CCS) needs to close down a connection to perform load balancing. Retry the message over -another XMPP connection. | -
The server side of Google Cloud Messaging (GCM) consists of two components:
-A full GCM implementation requires both a client implementation and a server -implementation. For more -information about implementing the client side, see -Implementing GCM Client.
- - -Before you can write client apps that use the GCM feature, you must -have an application server that meets the following criteria:
- -Here are the basic steps you follow to implement your 3rd-party app server:
- -Currently GCM provides two connection servers: -HTTP and XMPP (CCS). You can use them -separately or in tandem. XMPP (CCS) messaging differs from HTTP messaging in the following ways:
-This section gives an overview of sending messages. For details of message syntax, -see Server Reference.
- -Here is the general sequence of events that occurs when a 3rd-party application -server sends a message (the details vary depending on the platform):
-The following sections describe the basic components involved in -sending a request. See the Server Reference -for details.
- -Required. When your app server sends a message in GCM, it must specify a target.
-For HTTP you must specify the target as one of the following:
-registration_ids
: For sending to 1 or more devices (up to 1000).
-When you send a message to multiple registration IDs, that is called a multicast message.notification_key
: For sending to multiple devices owned by a single user.For CCS (XMPP) you must specify the target as:
-There are various options the 3rd-party app server can set when sending a downstream -message to a client app. See the -Server Reference for details. Here are a few examples of possible options:
- -If you want to test your request (either JSON or plain text) without delivering
-the message to the devices, you can set an optional HTTP parameter called
-dry_run
with the value true
. The result will be almost
-identical to running the request without this parameter, except that the message
-will not be delivered to the devices. Consequently, the response will contain fake
-IDs for the message and multicast parameters.
Optional. If you are including a payload in the message, you use the data
-parameter to include the payload. This applies for both HTTP and XMPP.
See the Server Reference for details on sending -and receiving messages.
- -This section has a discussion of general messaging topics.
- -Every message sent in GCM has the following characteristics:
-But despite these similarities, messages can behave very differently depending -on their particular settings. One major distinction between messages is whether -they are collapsed (where each new message replaces the preceding message) or not -collapsed (where each individual message is delivered). Every message sent in GCM -is either a "send-to-sync" (collapsible) message or a "message with -payload" (non-collapsible message).
- -A send-to-sync (collapsible) message is often a "tickle" that tells -a mobile application to sync data from the server. For example, suppose you have -an email application. When a user receives new email on the server, the server -pings the mobile application with a "New mail" message. This tells the -application to sync to the server to pick up the new email. The server might send -this message multiple times as new mail continues to accumulate, before the application -has had a chance to sync. But if the user has received 25 new emails, there's no -need to preserve every "New mail" message. One is sufficient. Another -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 GCM server -at any given time. In other words, the GCM server can simultaneously store 4 -different send-to-sync messages per device, each with a different collapse key. -For example, Device A can have A1, A2, A3, and A4. Device B can have B1, B2, B3, -and B4, and so on. If you exceed this number GCM will only keep 4 collapse keys, with no -guarantees about which ones they will be.
- -Unlike a send-to-sync message, every "message with payload" -(non-collapsible message) is delivered. The payload the message contains can be -up to 4kb. For example, here is a JSON-formatted message in an IM application in -which spectators are discussing a sporting event:
- -{ - "registration_id" : "APA91bHun4MxP5egoKMwt2KZFBaFUH-1RYqx...", - "data" : { - "Nick" : "Mario", - "Text" : "great match!", - "Room" : "PortugalVSDenmark", - }, -}- -
A "message with payload" is not simply a "ping" to the
-mobile application to contact the server to fetch data. In the aforementioned IM
-application, for example, you would want to deliver every message, because every
-message has different content. To specify a non-collapsible message, you simply
-omit the collapse_key
parameter. Thus GCM will send each message
-individually. Note that the order of delivery is not guaranteed.
GCM will store up to 100 non-collapsible messages. After that, all messages -are discarded from GCM, and a new message is created that tells the client how -far behind it is.
- -The application should respond by syncing with the server to recover the -discarded messages.
- -If your application does not need to use non-collapsible messages, collapsible -messages are a better choice from a performance standpoint. However, if you use -collapsible messages, remember that GCM only allows a maximum of 4 different collapse -keys to be used by the GCM server per registration ID at any given time. You must -not exceed this number, or it could cause unpredictable consequences.
- -You can use the time_to_live
parameter in the send request
-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:
-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.
-Or the sender itself might request
-that messages not be delivered until the device becomes active by using the
-delay_while_idle
flag. Finally, GCM might intentionally delay messages
-to prevent an application from consuming excessive resources and negatively
-impacting battery life.
When this happens, GCM will store the message and deliver 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.
- -Another advantage of specifying the expiration date for a message is that GCM
-will never throttle messages with a time_to_live
value of 0 seconds.
-In other words, GCM will guarantee 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, - "registration_ids" : ["xyz"], - "data" : { - "key1" : "value1", - "key2" : "value2", - }, - "time_to_live" : 3 -}, -- - -
GCM allows multiple parties to send messages to the same application. For -example, suppose your application is an articles aggregator with multiple -contributors, and you want each of them to be able to send a message when they -publish a new article. This message might contain a URL so that the application -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, all you need to do is have each sender generate its own -project number. Then include those IDs in the sender field, separated by commas, -when requesting a registration. Finally, share the registration ID with your -partners, and they'll be able to send messages to your application using their -own authentication keys.
- -Note that there is limit of 100 multiple senders.
- -When a 3rd-party 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 (see Throttling), -the message will be delivered right away.
- -If the device is connected but idle, the message will still be
-delivered right away unless the delay_while_idle
flag is set to true.
-Otherwise, it will be stored in the GCM servers until the device is awake. And
-that's where the collapse_key
flag plays a role: if there is already
-a message with the same collapse key (and registration ID) 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.
-Collapsible messages are also called send-to-sync messages.
Note: There is a limit on how many messages can
-be stored without collapsing. That limit is currently 100. If the limit is reached,
-all stored messages are discarded. Then 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.
-
-Likewise, there is a limit on how many collapse_key
s you can have for
-a particular device. GCM allows a maximum of 4 different collapse keys to be used
-by the GCM server per device
-any given time. In other words, the GCM server can simultaneously store 4 different
-send-to-sync messages, each with a different collapse key. If you exceed this number
-GCM will only keep 4 collapse keys, with no guarantees about which ones they will be.
-See Send-to-sync messages for more information.
-
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 will deliver all pending messages to the device, regardless of
-the delay_while_idle
flag. 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 ID. Future attempts to send a message to that device
-will get a NotRegistered
error. See
-How Unregistration Works for more information.
Although is not possible to track the status of each individual message, the -Google Cloud Console stats are broken down by messages sent to device, messages -collapsed, and messages waiting for delivery.
- -To prevent abuse (such as sending a flood of messages to a device) and -to optimize for the overall network efficiency and battery life of -devices, GCM implements throttling of messages using a token bucket -scheme. Messages are throttled on a per application and per collapse -key basis (including non-collapsible messages). Each application -collapse key is granted some initial tokens, and new tokens are granted -periodically therefter. Each token is valid for a single message sent to -the device. If an application collapse key exhausts its supply of -available tokens, new messages are buffered in a pending queue until -new tokens become available at the time of the periodic grant. Thus -throttling in between periodic grant intervals may add to the latency -of message delivery for an application collapse key that sends a large -number of messages within a short period of time. Messages in the pending -queue of an application collapse key may be delivered before the time -of the next periodic grant, if they are piggybacked with messages -belonging to a non-throttled category by GCM for network and battery -efficiency reasons.
- - diff --git a/docs/html/google/gcs/gcs-signup.jd b/docs/html/google/gcs/gcs-signup.jd deleted file mode 100644 index 7334cec..0000000 --- a/docs/html/google/gcs/gcs-signup.jd +++ /dev/null @@ -1,10 +0,0 @@ -page.title=Sign Up for Google Cloud Save - -@jd:body - -Sign up to be a trial partner for Google Cloud Save.
- - - -