From 0137175af92b631932c03660baf4f634b65001b8 Mon Sep 17 00:00:00 2001
From: kmccormick This document covers advanced topics for GCM. 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 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.
- 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 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 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. Whenever the application 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, it should try again or unregister from GCM. There are also two other scenarios that require special care: When an application is updated, it should invalidate its existing registration
-ID, as it is not guaranteed to work with the new version. Because there is no
-lifecycle method called when the application is updated, the best way to achieve
-this validation is by storing the current application version when a registration
-ID is stored. Then when the application is started, compare the stored value with
-the current application version. If they do not match, invalidate the stored data
-and start the registration process again. Similarly, you should not save the registration ID when an application is
-backed up. This is because the registration ID could become invalid by the time
-the application is restored, which would put the application in an invalid state
-(that is, the application thinks it is registered, but the server and GCM do not
-store that registration ID anymore—thus the application will not get more
-messages). On the server side, as long as the application is behaving well, everything
-should work normally. However, if a bug in the application 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 application. 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 When registration or unregistration fails, the app should retry the failed operation. In the simplest case, if your application attempts to register and GCM is not a
-fundamental part of the application, the application 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. If the register (or unregister) operation was synchronous, it could be retried
-in a simple loop. However, since it is asynchronous, the best approach is to schedule
-a {@link android.app.PendingIntent} to retry the operation.
-
- This section explains when you should unregister in GCM and what happens
-when you do. A registration ID (regID) represents a particular Android application running
-on a particular device. 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 regID has
-been compromised. In general, though, once an app has a regID, 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: The solution is to manage your own mapping between users, the regID, and
-individual messages: An application can be automatically unregistered after it is uninstalled from
-the device. However, this process does not happens right away, as Android does not
-provide an uninstall callback. What happens in this scenario is as follows: Note: The GCM client is the Google Cloud
-Messaging framework present on the device. 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 device.
-Eventually, the registration ID will be removed and the server will get a
- 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). These concepts are described in more
-detail in the following sections. 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, so it makes sense to have each new
-message replace the preceding message. The email and sports applications are cases where you would probably use the
-GCM 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: 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 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 message is delivered through a regular
- 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, because they put less
-of a burden on the device battery. 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 device at any given time. You must not exceed this number, or it could cause
-unpredictable consequences. The Time to Live (TTL) feature lets the sender specify the maximum lifespan
-of a message using the Here are some possible uses for this feature: GCM will usually deliver messages immediately after they are sent. However,
-this might not always be possible. For example, the device could be turned off,
-offline, or otherwise unavailable. In other cases, the sender itself might request
-that messages not be delivered until the device becomes active by using the
- 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 Here is an example of a JSON-formatted request that includes TTL: 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. This code snippet illustrates this feature. Senders are passed as an intent
-extra in a comma-separated list: Note that there is limit of 100 multiple senders. 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 keep track of whether a registration ID is from C2DM or GCM and use the proper endpoint. 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! The only change required in the application is replacing the email account passed in the sender parameter of the registration intent with the project number generated when signing up for the new service. For example: 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:Quickview
-
-
-
-
-
-In this document
-
-
-
-Lifetime of a Message
-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.
-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.
-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.NotRegistered
error. See
-How Unregistration Works for more information.Throttling
-Keeping the Registration State in Sync
-
-
-Canonical IDs
-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.Automatic Retry Using Exponential Back-Off
-
-Unregistration
-
-Why you should rarely unregister
-
-
-
-
-
-
-
-
-
-How unregistration works
-
-
-
-
-false
.
-NotRegistered
error message to the 3rd-party server.NotRegistered
error, without any further action being required from
-the 3rd-party server (this scenario happens frequently while an application is
-being developed and tested).Send-to-Sync vs. Messages with Payload
-
-
-
-
-Send-to-sync messages
-
-collapse_key
parameter. A collapse key is an arbitrary
-string that is used to collapse a group of like messages when the device is offline,
-so that only the most recent message gets sent to the client. For example,
-"New mail," "Updates available," and so onMessages with payload
-
-{
- "registration_id" : "APA91bHun4MxP5egoKMwt2KZFBaFUH-1RYqx...",
- "data" : {
- "Nick" : "Mario",
- "Text" : "great match!",
- "Room" : "PortugalVSDenmark",
- },
-}
-
-collapse_key
parameter. Thus GCM will send each message
-individually. Note that the order of delivery is not guaranteed.com.google.android.c2dm.intent.RECEIVE
intent with the
-extra message_type
, for which the value is always the string
-"deleted_messages".Which should I use?
- Setting an Expiration Date for a Message
-time_to_live
parameter in the send request.
-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.
-
-Background
-delay_while_idle
flag. Finally, GCM might intentionally delay messages
-to prevent an application from consuming excessive resources and negatively
-impacting battery life.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.
-{
- "collapse_key" : "demo",
- "delay_while_idle" : true,
- "registration_ids" : ["xyz"],
- "data" : {
- "key1" : "value1",
- "key2" : "value2",
- },
- "time_to_live" : 3
-},
-
-
-
-Receiving Messages from Multiple Senders
-
-Intent intent = new Intent(GCMConstants.INTENT_TO_GCM_REGISTRATION);
-intent.setPackage(GSF_PACKAGE);
-intent.putExtra(GCMConstants.EXTRA_APPLICATION_PENDING_INTENT,
- PendingIntent.getBroadcast(context, 0, new Intent(), 0));
-String senderIds = "968350041068,652183961211";
-intent.putExtra(GCMConstants.EXTRA_SENDER, senderIds);
-ontext.startService(intent);
-
-
-Relationship between C2DM and GCM
-Migrating Your Apps
Client changes
-Intent registrationIntent = new Intent("com.google.android.c2dm.intent.REGISTER");
-// sets the app name in the intent
-registrationIntent.putExtra("app", PendingIntent.getBroadcast(this, 0, new Intent(), 0));
-registrationIntent.putExtra("sender", senderID);
-startService(registrationIntent);
+Server changes
See Also
+
Note: See -Implementing GCM Server for a list of all the message +
Note: See the +Server Reference for a list of all the message parameters and which connection server(s) supports them.
Note: See -Implementing GCM Server for a list of all the message +
Note: See the +Server Reference for a list of all the message parameters and which connection server(s) supports them.
The following table lists NACK error codes. Unless otherwise +
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}.
- - -Error Code | -Description | -
---|---|
{@code BAD_ACK} | -The ACK message is improperly formed. | -
{@code BAD_REGISTRATION} | -The device has a registration ID, but it's invalid or expired. | -
{@code CONNECTION_DRAINING} | -The message couldn't be processed because the connection is draining. The -message should be immediately retried over another connection. | -
{@code DEVICE_UNREGISTERED} | -The device is not registered. | -
{@code INTERNAL_SERVER_ERROR} | -The server encountered an error while trying to process the request. | -
{@code INVALID_JSON} | -The JSON message payload is not valid. | -{@code DEVICE_MESSAGE_RATE_EXCEEDED} | -The rate of messages to a particular device is too high. You should reduce -the number of messages sent to this device and should not immediately retry -sending to this device. This error code is replacing {@code QUOTA_EXCEEDED}. | - -
{@code SERVICE_UNAVAILABLE} | -CCS is not currently able to process the message. The - message should be retried over the same connection using exponential backoff - with an initial delay of 1 second. | -
You can also get a stanza error in certain cases. diff --git a/docs/html/google/gcm/client.jd b/docs/html/google/gcm/client.jd index d44ee3c..9cb3f84 100644 --- a/docs/html/google/gcm/client.jd +++ b/docs/html/google/gcm/client.jd @@ -1,4 +1,4 @@ -page.title=Implementing GCM Client +page.title=Implementing GCM Client on Android page.tags=cloud,push,messaging @jd:body @@ -15,8 +15,8 @@ page.tags=cloud,push,messaging
A Google Cloud Messaging (GCM) client is a GCM-enabled app that runs on an +
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 -GCM APIs. -The client helper library that was offered in previous versions of GCM still works, -but it has been superseded by the more efficient - -GCM APIs.
+{@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 @@ -58,7 +70,7 @@ registration ID), and a broadcast receiver to receive messages sent by GCM.
To write your client application, use the -GCM APIs. +{@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.
@@ -88,9 +100,6 @@ If you're using Android Studio, this is the string to add to the 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.GET_ACCOUNTS
permission as GCM requires
-a Google account (necessary only if if the device is running a version lower than
-Android 4.0.4)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.com.google.android.c2dm.intent.RECEIVE
, with
the category set
as applicationPackage
. The receiver should require the
-com.google.android.c2dm.SEND
permission, so that only the GCM
+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}.
@@ -324,8 +333,8 @@ private String getRegistrationId(Context context) {
return "";
}
// Check if app was updated; if so, it must clear the registration ID
- // since the existing regID is not guaranteed to work with the new
- // app version.
+ // 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) {
@@ -340,14 +349,14 @@ private String getRegistrationId(Context context) {
*/
private SharedPreferences getGCMPreferences(Context context) {
// This sample app persists the registration ID in shared preferences, but
- // how you store the regID in your app is up to you.
+ // 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 regID. {@code getRegistrationId()} calls +to indicate that the app needs to get a new registration ID. {@code getRegistrationId()} calls the following method to check the app version:
/** @@ -400,7 +409,7 @@ private void registerInBackground() { // will send upstream messages to a server that echo back the // message using the 'from' address in the message. - // Persist the regID - no need to register again. + // Persist the registration ID - no need to register again. storeRegistrationId(context, regid); } catch (IOException ex) { msg = "Error :" + ex.getMessage(); @@ -433,7 +442,8 @@ private void sendRegistrationIdToBackend() {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 regID. You might choose to use a different approach in your app:
+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 @@ -455,64 +465,22 @@ private void storeRegistrationId(Context context, String regId) {+ +Handle registration errors
As stated above, an Android app must register with GCM servers and get a registration ID -(regID) before it can receive messages. A given regID is not guaranteed to last indefinitely, -so the first thing your app should always do is check to make sure it has a valid regID -(as shown in the code snippets above).
+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 regID, your app should be prepared to handle +
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 GCM-enabled apps from the device to make +the user to delete some of the other client apps from the device to make room for the new one.
- -Send a message
-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(""); - } -} Receive a message
+Receive a downstream message
As described above in Step 2, the app includes a {@link android.support.v4.content.WakefulBroadcastReceiver} for the
+intent. A broadcast receiver is the mechanism GCM uses to deliver messages.com.google.android.c2dm.intent.RECEIVE
-intent. A broadcast receiver is the mechanism GCM uses to deliver messages. When {@code onClick()} -calls {@code gcm.send()}, it triggers the broadcast receiver's {@code onReceive()} -method, which has the responsibility of making sure that the GCM message gets handled.A {@link android.support.v4.content.WakefulBroadcastReceiver} is a special type of broadcast receiver that takes care of creating and managing a @@ -646,6 +614,46 @@ public class GcmIntentService extends IntentService { } }
Send an upstream message
+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(""); + } +} Running the Sample
To run the sample:
diff --git a/docs/html/google/gcm/gcm.jd b/docs/html/google/gcm/gcm.jd index 3d6594d..4e345b3 100644 --- a/docs/html/google/gcm/gcm.jd +++ b/docs/html/google/gcm/gcm.jd @@ -9,58 +9,24 @@ page.title=Overview -Google Cloud Messaging (GCM) for Android is a free service that helps -developers send data from servers to their Android applications on Android -devices, and upstream messages from the user's device back to the cloud. -This could be a lightweight message telling the Android application +
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 application that it is out of sync with the back end), +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 the target -Android application running on the target device.
- -To jump right into using GCM with your Android - applications, see Getting Started.
+service handles all aspects of queueing of messages and delivery to and from +the target client app. -Here are the primary characteristics of Google Cloud -Messaging (GCM):
- -
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 running on an Android device:
+server, and a GCM-enabled client app. For example, this diagram shows GCM +communicating with a client app on an Android device: @@ -163,84 +112,196 @@ server, and a GCM-enabled client app running on an Android device:This is how these components interact:
These processes are described in more detail below.
+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.
-The first time the Android application needs to use the messaging service, it
-calls the
-{@code GoogleCloudMessaging} method {@code register()}, as discussed in
-Implementing GCM Client.
-The {@code register()} method returns a registration ID. The Android
-application should store this ID for later use (for instance,
-to check in onCreate()
if it is already registered).
+
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.
-Here is the sequence of events that occurs when the application server sends a -message:
+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.
-An Android application can unregister GCM if it no longer wants to receive -messages.
+In particular, you should never unregister your app as a mechanism for +logout or for switching between users, for the following reasons:
+ +This is the sequence of events that occurs when an Android application -installed on a mobile device receives a message:
+To make sure that messages go to the intended user:
+An 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:
com.google.android.c2dm.intent.RECEIVE
Intent as a set of
-extras.com.google.android.c2dm.intent.RECEIVE
Intent
-by key and processes the data.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).
To enable the GCM service:
@@ -71,7 +71,7 @@ purposes, you can use {@code 0.0.0.0/0}.Note: If you need to rotate the key, click Regenerate key. A new key will be created. If you think the key has been @@ -84,16 +84,11 @@ compromised and you want to delete it immediately, click Delete implementing GCM. Here is an overview of the basic steps:
See -Implementing GCM Server for a list of all the message +
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 to
-https://android.googleapis.com/gcm/send
.
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.
+ Content-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 @@ -71,26 +76,30 @@ Authorization:key=AIzaSyB-1uEai2WiUapxCs2Q0GZYzPu7Udno5aA ... }, }-
-
Note: If Content-Type
is omitted, the format
-is assumed to be plain text.
The HTTP body content depends on whether you're using JSON or plain text. See -Implementing GCM Server for a list of all the +the Server Reference for a list of all the parameters your JSON or plain text message can contain.
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" @@ -112,10 +121,25 @@ just one recipient) using JSON: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 Android devices to receive messages. +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 @@ -127,54 +151,12 @@ contained in the IP blocks listed in Google's ASN of 15169.
There are two possible outcomes when trying to send a message:
When the message is processed successfully, the HTTP response has a 200 status -and the body contains more information about the status of the message -(including possible errors). When the request is rejected, -the HTTP response contains a non-200 status code (such as 400, 401, or 503).
- -The following table summarizes the statuses that the HTTP response header might -contain. Click the troubleshoot link for advice on how to deal with each type of -error.
-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 Interpreting a success response -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 |
-
When a JSON request is successful (HTTP status code 200), the response body contains a JSON object with the following fields:
@@ -241,8 +223,8 @@ code>registration_ids passed in the request (using the same index). request.NotRegistered
, you should remove the registration
ID from your server database because the application was uninstalled from the
-device or it does not have a broadcast receiver configured to receive
-com.google.android.c2dm.intent.RECEIVE
intents.com.google.android.c2dm.intent.REGISTRATION
intent and that you're
+sure it matches the registration ID the client app receives and that you're
not truncating it or adding additional characters.
InvalidRegistration
.MismatchSenderId
.
com.google.android.c2dm.intent.UNREGISTER
-
intent.com.google.android.c2dm.intent.RECEIVE
-intents.from
or any value
-prefixed by google.
) that is used internally by GCM in the
-com.google.android.c2dm.intent.RECEIVE
Intent and cannot be used.
+prefixed by google.
) that is used internally by GCM and therefore cannot be used.
Note that some words (such as 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.
@@ -354,9 +330,9 @@ authenticated. Possible causes are: Authorization
header
-is the correct API key associated with your project. You can check the validity
-of your API key by running the following command:# api_key=YOUR_API_KEY @@ -405,8 +381,7 @@ Happens when the HTTP status code is between 501 and 599, or when the
error
field of a JSON
object in the results array is InternalServerError
.
@@ -488,7 +463,7 @@ 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.
Requirements
@@ -508,7 +483,7 @@ version 1.6 or later.For the Android application:
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 new file mode 100644 index 0000000..a94e727 --- /dev/null +++ b/docs/html/google/gcm/server-ref.jd @@ -0,0 +1,763 @@ +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 2 components:
+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:
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.
Currently GCM provides two connection servers: -HTTP and CCS (XMPP). You can use them -separately or in tandem. CCS messaging differs from GCM HTTP messaging in the following ways:
+HTTP and XMPP (CCS). You can use them +separately or in tandem. XMPP (CCS) messaging differs from HTTP messaging in the following ways:Before you can write client Android applications that use the GCM feature, you must -have an application server that meets the following criteria:
+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:
+server sends a message (the details vary depending on the platform):The following sections describe the basic requirements for -sending messages.
+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:
+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):
+For CCS (XMPP) you must specify the target as:
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 CCS.
The following table lists the parameters that a 3rd-party app server might -include in the JSON messages it sends to a connection server. See the "Where Supported" -column for information about which connection servers support that particular -parameter.
- - - -Parameter | -Description | -Where Supported | -to |
-In CCS, this parameter is used in place of registration_ids to
-specify the recipient of a message. Its value must be a registration ID.
-The value is a string. Required. |
-CCS | - -
---|---|---|
message_id |
-In CCS, this parameter uniquely identifies a message in an XMPP connection. -The value is a string that uniquely identifies the associated message. Required. | -CCS | -
message_type |
-In CCS, this parameter indicates a special status message, typically sent by the system. -However, your app server also uses this parameter to send an 'ack' or 'nack' -message back to the CCS connection server. For more discussion of this topic, see -Cloud Connection Server. The value is a string. Optional. | -CCS | -
registration_ids |
- This parameter specifies a string array containing the list of devices -(registration IDs) receiving the -message. It must contain at least 1 and at most 1000 registration IDs. To send a -multicast message, you must use JSON. For sending a single message to a single -device, you could use a JSON object with just 1 registration id, or plain text -(see below). A request must include a recipient—this can be either a -registration ID, an array of registration IDs, or a {@code notification_key}. -Required. | -HTTP | -
notification_key |
- This parameter specifies a string that maps a single user to multiple -registration IDs associated -with that user. This allows a 3rd-party server to send a single message to -multiple app instances (typically on multiple devices) owned by a single user. -A 3rd-party 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. For more discussion -of this topic, see User Notifications. Optional. - | -HTTP. This feature is supported in CCS, but you use it by -specifying a notification key in the "to" field. | -
collapse_key |
- This parameter specifies an arbitrary string (such as
-"Updates Available") that is used
-to collapse a group of like messages
-when the device is offline, so that only the last message gets sent to the
-client. This is intended to avoid sending too many messages to the phone when it
-comes back online. Note that since there is no guarantee of the order in which
-messages get sent, the "last" message may not actually be the last
-message sent by the application server. Messages with collapse keys are also called
-send-to-sync messages.
- -Note: 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. -If you exceed -this number GCM will only keep 4 collapse keys, with no guarantees about which -ones they will be. See Advanced Topics for more -discussion of this topic. Optional. |
-CCS, HTTP | -
data |
- This parameter specifies a JSON object whose fields represents the
-key-value pairs of the message's
-payload data. If present, the payload data will be
-included in the Intent as application data, with the key being the extra's name.
-For instance, "data":{"score":"3x1"} would result in an intent extra
-named score whose value is the string 3x1 .
-There is no limit on the number of key/value pairs, though there is a limit on
-the total size of the message (4kb). The values could be any JSON object, but we
-recommend using strings, since the values will be converted to strings in the GCM
-server anyway. If you want to include objects or other non-string data types
-(such as integers or booleans), you have to do the conversion to string yourself.
-Also note that the key cannot be a reserved word (from or any word
-starting with google. ). Using words defined in this table as field
-names (such as collapse_key ) could yield unpredictable outcomes and
-is not recommended. Optional. |
-CCS, HTTP | -
delay_while_idle |
- This parameter indicates that the message should not be sent immediately
-if the device is idle. The server will wait for the device to become active, and
-then only the last message for each collapse_key value will be
-sent. The default value is false , and must be a JSON boolean. Optional. |
-CCS, HTTP | -
time_to_live |
- This parameter specifies how long (in seconds) the message should be kept on GCM -storage if the device is offline. Optional (default time-to-live is 4 weeks, and must be set as -a JSON number). | -CCS, HTTP | -
restricted_package_name |
- This parameter specifies a string containing the package -name of your application. When set, messages -are only sent to registration IDs that match the package name. Optional. - | -HTTP | -
dry_run |
- This parameter allows developers to test a request without actually
-sending a message. Optional. The default value is false , and must
-be a JSON boolean.
- |
-HTTP | -
delivery_receipt_requested |
- This parameter lets you request confirmation of message delivery. When
-this parameter is set to true , CCS sends a
-delivery receipt when a device confirms that it received a message sent by CCS.
-The default value is false , and must be a JSON boolean. Optional.-This parameter relates to -delivery receipts. - |
- CCS | -
message_status |
- This parameter specifies the status of the receipt message.
-The parameter appears inside the
-"data" field of a
-delivery receipt message. Currently the only possible value
-is MESSAGE_SENT_TO_DEVICE , which indicates that a device acknowledges
-receiving a message sent by CCS.-This parameter relates to -delivery receipts. |
- CCS | -
original_message_id |
- The value of this parameter is the ID of the original message that the server sent to
-the device. This parameter appears inside the "data" field of a
-delivery receipt message. -This parameter relates to -delivery receipts. |
- CCS | -
device_registration_id |
- For the purpose of tracking the delivery receipt, this parameter lists
-the registration ID of the device to which a given message was sent. This parameter
-appears inside the "data" field of a
-delivery receipt message. -This parameter relates to -delivery receipts. |
- CCS | -
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 or JSON parameter called
+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.
If you are using plain text instead of JSON, the message parameters must be set as -HTTP parameters sent in the body, and their syntax is slightly different, as -described in the following table: - -
-Parameter | -Description | -
---|---|
registration_id |
- This parameter specifies the registration ID of the single device -receiving the message. -Required. | -
collapse_key |
- Same as JSON (see previous table). Optional. | -
data.<key> |
-
- This parameter specifies payload data, expressed as parameters
-prefixed with data. and
-suffixed as the key. For instance, a parameter of data.score=3x1 would
-result in an intent extra named score whose value is the string
-3x1 . There is no limit on the number of key/value parameters, though
-there is a limit on the total size of the message. Also note that the key cannot
-be a reserved word (from or any word starting with
-google. ). Using words defined in this table as field
-names (such as collapse_key ) could yield unpredictable outcomes and
-is not recommended. Optional. |
-
-
delay_while_idle |
- This parameter specifies whether messages should be delivered when the device
-is asleep. A value of 1 or true indicates
-true , and anything else indicates false . Optional. The default
-value is false . |
-
time_to_live |
- Same as JSON (see previous table). Optional. | -
restricted_package_name |
- Same as JSON (see previous table). Optional. - | -
dry_run |
- Same as JSON (see previous table). Optional. - | -
This is the sequence of events that occurs when an Android application -installed on a mobile device receives a message:
+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.
-com.google.android.c2dm.intent.RECEIVE
Intent as a set of
-extras.com.google.android.c2dm.intent.RECEIVE
Intent
-by key and processes the data.See the documentation for each connection server for more detail on how it -handles responses.
diff --git a/docs/html/google/google_toc.cs b/docs/html/google/google_toc.cs index 0c48a0a..4e8e638 100644 --- a/docs/html/google/google_toc.cs +++ b/docs/html/google/google_toc.cs @@ -169,22 +169,15 @@ HTTP +