Home | History | Annotate | Download | only in gcm
      1 page.title=GCM Architectural Overview
      2 @jd:body
      3 
      4 <div id="qv-wrapper">
      5 <div id="qv">
      6 
      7 <h2>Quickview</h2>
      8 
      9 <ul>
     10 <li>Get an introduction to key GCM terms and concepts.</li>
     11 <li>Learn the basic features of a GCM application.</li>
     12 <li>Understand the role of the 3rd-party application server, and how to send messages and process results.</li>
     13 </ul>
     14 
     15 
     16 <h2>In this document</h2>
     17 
     18 <ol class="toc">
     19   <li><a href="#intro">Introduction</a> </li>
     20   <li><a href="#arch">Architectural Overview</a>
     21     <ol>
     22       <li><a href="#lifecycle">Lifecycle Flow</a></li>
     23       <li><a href="#user">What Does the User See?</a></li>
     24     </ol>
     25   </li>
     26   <li><a href="#writing_apps">Writing Android Applications that use GCM</a>
     27     <ol>
     28     <li><a href="#manifest">Creating the Manifest</a></li>
     29     <li><a href="#registering">Registering for GCM</a></li>
     30     <li><a href="#unregistering">Unregistering from GCM</a></li>
     31     <li><a href="#handling_intents">Handling Intents sent by GCM</a>
     32       <ol>
     33         <li><a href="#handling_reg">Handling Registration Results</a></li>
     34         <li><a href="#received_data">Handling Received Data</a></li>
     35       </ol>
     36     </li>
     37     <li><a href="#testing">Developing and Testing Your Android Applications</a></li>
     38     </ol>
     39   </li>
     40   <li><a href="#server">Role of  the 3rd-party Application Server</a>
     41     <ol class="toc">
     42       <li><a href="#send-msg">Sending Messages</a>
     43         <ol>
     44           <li><a href="#request">Request format</a></li>
     45           <li><a href="#response">Response format</a></li>
     46         </ol>
     47       </li>
     48     </ol>
     49     <li><a href="#stats">Viewing statistics</a>
     50   </li>
     51   <li><a href="#example">Examples</a></li>
     52 </ol>
     53 
     54 
     55 
     56 </div>
     57 </div>
     58 
     59 <p>Google Cloud Messaging for Android (GCM) is a free service that helps
     60 developers  send data from servers to their Android applications on  Android
     61 devices. This could be a lightweight message telling the Android application
     62 that there is new data to be fetched from the server (for instance, a movie
     63 uploaded by a friend), or it could be a message containing up to 4kb of payload
     64 data (so apps like instant messaging can consume the message directly). The GCM
     65 service handles all aspects  of queueing of messages and delivery to the target
     66 Android application running  on the target device.</p>
     67   
     68   
     69 <p class="note"> To jump right into using GCM with your Android
     70   applications, see the instructions in <a href="gs.html">Getting Started</a>.</p>
     71 
     72 
     73 
     74 
     75 <h2 id="intro">Introduction</h2>
     76 
     77 <p>Here are the primary characteristics of Google Cloud 
     78 Messaging (GCM):</p>
     79 
     80 <ul>
     81   <li>It allows 3rd-party application servers to send messages to
     82 their Android applications.</li>
     83   <li>GCM makes no guarantees about delivery or the order of messages.</li>
     84   <li>An Android application on an Android device doesn't need to be running to receive
     85 messages. The system will wake up the Android application via Intent broadcast when the  message arrives, as long as the application is set up with the proper
     86 broadcast receiver and permissions.</li>
     87   <li>It does not provide any  built-in user interface or other handling for
     88 message data. GCM  simply passes raw message data received straight to the
     89 Android application,  which has full control of how to handle it. For example, the
     90 application might post a notification, display a custom user interface, or 
     91 silently sync data.</li>
     92   <li>It requires devices running Android 2.2 or higher that also have the
     93 Google Play Store application installed, or or an emulator running Android 2.2 with Google APIs. However, you are not limited to deploying your
     94 Android applications through Google Play Store.</li>
     95   <li>It uses an existing connection for Google services. For pre-3.0 devices, this requires users to
     96 set up their Google account on their mobile devices. A Google account is not a requirement on devices running Android 4.0.4 or higher.</li>
     97 </ul>
     98 <h2 id="arch">Architectural Overview</h2>
     99 <p>This section gives an overview of how GCM works. </p>
    100 <p>This table summarizes the key terms and concepts involved in GCM. It is
    101 divided into these categories:</p>
    102 <ul>
    103   <li><strong>Components</strong> &mdash; The physical entities that play a role in
    104 GCM.</li>
    105   <li><strong>Credentials</strong> &mdash; The IDs and tokens that are used in
    106 different stages of GCM to ensure that all parties have been authenticated, and
    107 that the message is going to the correct place.</li>
    108 </ul>
    109 
    110 <table>
    111   <tr>
    112     <th colspan="2">Components</th>
    113   </tr>
    114   <tr>
    115     <td width="165"><strong>Mobile Device</strong></td>
    116     <td width="1176">The device that is running an Android application that uses
    117 GCM. This must be a 2.2 Android device that has Google Play Store installed, and it must
    118 have at least one logged in Google account if the device is running a version lower than Android 4.0.4. Alternatively, for testing you can use an emulator running Android 2.2 with Google APIs.</td>
    119   </tr>
    120   <tr>
    121     <td><strong>3rd-party Application Server</strong></td>
    122     <td>An application server that  developers  set up as part of implementing
    123 GCM in their applications. The 3rd-party application server sends data to an
    124 Android application on the device via the GCM server.</td>
    125   </tr>
    126   <tr>
    127     <td><strong>GCM Servers</strong></td>
    128     <td>The Google servers involved in taking messages from the 3rd-party
    129 application server and sending them to the device. </td>
    130   </tr>
    131   <tr>
    132     <th colspan="2"><strong>Credentials</strong></th>
    133   </tr>
    134   <tr>
    135     <td><strong>Sender ID</strong></td>
    136     <td>A project ID you acquire from the API console, as described in <a href="gs.html#create-proj">Getting Started</a>. The sender
    137 ID is used in the <a href="#registering">registration process</a> to identify an
    138 Android application that is permitted to send messages to the device.</td>
    139   </tr>
    140   <tr>
    141     <td><strong>Application ID</strong></td>
    142     <td>The Android application that is registering to receive messages. The Android application
    143 is identified by the package name from the <a href="#manifest">manifest</a>.
    144 This  ensures that the messages are targeted to the correct Android application.</td>
    145   </tr>
    146   <tr>
    147     <td><strong>Registration ID</strong></td>
    148     <td>An ID issued by the GCM servers to the Android application that allows
    149 it to receive messages. Once the Android application has the registration ID, it sends
    150 it to the 3rd-party application server, which uses it to identify each device 
    151 that has registered to receive messages for a given Android application. In other words,
    152 a registration ID is tied to a particular Android application running on a particular
    153 device.</td>
    154   </tr>
    155   <tr>
    156     <td><strong>Google User Account</strong></td>
    157     <td>For GCM to work, the mobile device must include at least one Google account if the device is running a version lower than Android 4.0.4.</td>
    158   </tr>
    159   <tr>
    160     <td><strong>Sender Auth Token</strong></td>
    161     <td>An API key that is saved on the 3rd-party application
    162 server that gives the application server authorized access to Google services.
    163 The API key is included in the header of POST requests  that send messages.</td>
    164   </tr>
    165 </table>
    166 
    167 <h3 id="lifecycle">Lifecycle Flow</h3>
    168 
    169 <p>Here are the primary processes involved in cloud-to-device messaging:</p>
    170 
    171 <ul>
    172   <li><a href="#register">Enabling GCM</a>. An Android application running on a
    173 mobile device registers to receive messages.</li>
    174   <li><a href="#push-process">Sending a message</a>. A 3rd-party application
    175 server sends messages to the device.</li>
    176   <li><a href="#receiving">Receiving a message</a>. An Android application
    177 receives a message from a GCM server.</li>
    178 </ul>
    179 
    180 <p>These processes are described in more detail below.</p>
    181 
    182 <h4 id="register">Enabling GCM</h4>
    183 
    184 <p>This is the sequence of events that occurs when an Android application
    185 running on a mobile device registers to receive messages:<span
    186 class="red-text"></span></p>
    187 
    188 <ol>
    189   <li>The first time the Android application needs to use the messaging service, it
    190 fires off a registration Intent to a GCM server. 
    191     <p>This registration Intent
    192 (<code>com.google.android.c2dm.intent.REGISTER</code>) includes the sender ID, and the Android application ID.</p>
    193 <p class="note"><strong>Note:</strong> Because there is no lifecycle method that is called when the application is run for
    194 the first time, the registration intent should be sent on <code>onCreate()</code>, but only if the application is not registered yet.
    195 </p>
    196   </li>
    197   <li>If the registration is successful, the GCM server broadcasts a <code>com.google.android.c2dm.intent.REGISTRATION</code> intent which gives the Android application  a registration
    198 ID. 
    199     <p>The Android application should store this ID for later use (for instance, to check on <code>onCreate()</code> if it is already registered). 
    200 Note that Google may periodically refresh the registration ID, so you should design your Android application
    201 with the understanding that the <code>com.google.android.c2dm.intent.REGISTRATION</code> intent may be called
    202 multiple times. Your Android application needs to be able to respond
    203 accordingly.</p></li>
    204   <li>To complete the registration, the Android application sends the registration ID to
    205 the application server. The application server typically stores the registration
    206 ID in a database. </li>
    207 </ol>
    208 
    209 <p>The registration ID lasts until the Android application explicitly unregisters
    210 itself, or until Google refreshes the registration ID for your Android application.</p>
    211 
    212 <p class="note"><strong>Note:</strong> When users uninstall an application, it is not automatically unregistered on GCM. It is only  unregistered when the GCM server tries to send a message to the device and the device answers that the application is uninstalled or it does not have a broadcast receiver configured to receive <code>com.google.android.c2dm.intent.RECEIVE</code> intents. At that point, you server should mark the device as unregistered (the server will receive a <code><a href="#unreg_device">NotRegistered</a></code> error).
    213   <p>
    214 Note that it might take a few minutes for the registration ID to be completed removed from the GCM server. So if the 3rd party server sends a message during this time, it will get a valid message ID, even though the message will not be delivered to the device.</p>
    215 </p>
    216 
    217 <h4 id="push-process">Sending a Message</h4>
    218 
    219 <p>For an application server to send a  message to an Android application, the following things must be in
    220 place:</p>
    221 
    222 <ul>
    223   <li>The Android application has a registration ID that allows it to receive messages
    224 for a particular device.</li>
    225   <li>The 3rd-party application server has stored the registration ID.</li>
    226 
    227 
    228 
    229 <li>An API key. This is something that the developer must have already
    230 set up on the application server for the Android application (for more discussion, see
    231 <a href="#server">Role of the 3rd-party Application Server</a>). Now it will
    232 get used to send messages to the device. </li>
    233 </ul>
    234 
    235 <p>Here is the sequence of events that occurs when the application server sends a 
    236 message:</p>
    237 
    238 <ol>
    239   <li>The application server sends a  message to  GCM servers.</li>
    240   <li>Google enqueues and stores the message in case the device is
    241 offline.</li>
    242   <li>When the device is online, Google sends the message to the device. </li>
    243   <li>On the device, the system  broadcasts the  message to the specified
    244 Android application via Intent broadcast with proper permissions, so that only the
    245 targeted Android application gets the message. This wakes the Android application up. The
    246 Android application does not need to be running beforehand to receive the message.</li>
    247   <li>The Android application processes the message. If the Android application is doing
    248 non-trivial processing, you may want to grab a {@link android.os.PowerManager.WakeLock} and do any processing in a Service.</li>
    249 </ol>
    250 
    251 <p> An Android application can  unregister GCM if it no longer wants to receive 
    252 messages.</p>
    253 
    254 <h4 id="receiving">Receiving a Message</h4>
    255 
    256 <p>This is the sequence of events that occurs when an Android application
    257 installed on a mobile device receives a message:</p>
    258 
    259 <ol>
    260   <li>The system receives the incoming message and extracts the raw key/value
    261 pairs from the message payload, if any.</li>
    262   <li>The system passes the key/value pairs to the targeted Android application
    263 in a <code>com.google.android.c2dm.intent.RECEIVE</code> Intent as a set of
    264 extras.</li>
    265   <li>The Android application extracts the raw data
    266 from the <code>com.google.android.c2dm.intent.RECEIVE</code><code> </code>Intent by key and processes the data.</li>
    267 </ol>
    268 
    269 <h3 id="user">What Does the User See?</h3>
    270 
    271 <p>When mobile device users install Android applications that include GCM, the Google Play Store will inform them that the Android application
    272 includes GCM. They must approve the use of this feature to install the
    273 Android application. </p>
    274 
    275 <h2 id="writing_apps">Writing Android Applications that Use GCM</h2>
    276 
    277 <p>To write Android applications that use GCM, you must have an application
    278 server that can perform the tasks described in <a href="#server">Role of the
    279 3rd-party Application Server</a>. This section describes the steps you take to
    280 create a client application that uses GCM.</p>
    281 
    282 <p>Remember that there is no user interface associated with  GCM.
    283 However you choose to process messages in your Android application is up to you.</p>
    284 
    285 <p>There are two primary steps involved in writing a client Android application:</p>
    286 
    287 <ul>
    288   <li>Creating a manifest that contains the permissions the Android application needs to
    289 use GCM.</li>
    290   <li>Implementing your  code. To use GCM, this implementation must
    291 include:
    292     <ul>
    293       <li>Code to start and stop the registration service.</li>
    294       <li>Receivers for the <code>com.google.android.c2dm.intent.RECEIVE</code> and <code>com.google.android.c2dm.intent.REGISTRATION</code> intents.</li>
    295     </ul>
    296   </li>
    297 </ul>
    298 
    299 <h3 id="manifest">Creating the Manifest</h3>
    300 
    301 <p>Every Android application must have an <code>AndroidManifest.xml</code> file (with
    302 precisely that name) in its root directory. The manifest presents essential
    303 information about the Android application to the Android system, information the
    304 system must have before it can run any of the Android application's code (for more
    305 discussion of the manifest file, see the <a href="{@docRoot}guide/topics/manifest/manifest-intro.html">Android Developers Guide</a>. To use the GCM feature, the
    306 manifest must include the following:</p>
    307 
    308 <ul>
    309   <li>The <code>com.google.android.c2dm.permission.RECEIVE</code> permission so the Android application can register and receive messages.</li>
    310   <li>The <code>android.permission.INTERNET</code> permission so the Android application can send the registration ID to the 3rd party server.</li>
    311   <li>The <code>android.permission.GET_ACCOUNTS</code> permission as GCM requires a Google account (necessary only if if the device is running a version lower than Android 4.0.4)</li>
    312   <li>The <code>android.permission.WAKE_LOCK</code> permission so the application can keep the processor from sleeping when a message is received.</li>
    313   <li>An <code>applicationPackage + &quot;.permission.C2D_MESSAGE</code> permission to prevent other Android applications from registering and receiving the Android application's
    314 messages. The permission name must exactly match this pattern&mdash;otherwise the Android application will not receive the messages.</li>
    315   <li>A receiver for <code>com.google.android.c2dm.intent.RECEIVE</code> and <code>com.google.android.c2dm.intent.REGISTRATION</code>, with the category set
    316 as <code>applicationPackage</code>. The receiver should require the <code>com.google.android.c2dm.SEND</code> permission, so that only the GCM
    317 Framework can send a message to it. Note that both registration and the receiving
    318 of messages are implemented as <a href="{@docRoot}guide/components/intents-filters.html">Intents</a>.</li>
    319   <li>An intent service to handle the intents received by the broadcast receiver.</li>
    320   <li>If the GCM feature is critical to the Android application's function, be sure to
    321 set <code>android:minSdkVersion=&quot;8&quot;</code> in the manifest. This
    322 ensures that the Android application cannot be installed in an environment in which it
    323 could not run properly. </li>
    324 </ul>
    325 
    326 <p>Here are excerpts from a manifest that supports GCM:</p>
    327 
    328 <pre class="prettyprint pretty-xml">
    329 &lt;manifest package="com.example.gcm" ...&gt;
    330 
    331     &lt;uses-sdk android:minSdkVersion="8" android:targetSdkVersion="16"/&gt;
    332     &lt;uses-permission android:name="android.permission.INTERNET" /&gt;
    333     &lt;uses-permission android:name="android.permission.GET_ACCOUNTS" /&gt;
    334     &lt;uses-permission android:name="android.permission.WAKE_LOCK" /&gt;
    335     &lt;uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" /&gt;
    336 
    337     &lt;permission android:name="com.example.gcm.permission.C2D_MESSAGE" 
    338         android:protectionLevel="signature" /&gt;
    339     &lt;uses-permission android:name="com.example.gcm.permission.C2D_MESSAGE" /&gt;
    340 
    341     &lt;application ...&gt;
    342         &lt;receiver
    343             android:name=".MyBroadcastReceiver"
    344             android:permission="com.google.android.c2dm.permission.SEND" &gt;
    345             &lt;intent-filter&gt;
    346                 &lt;action android:name="com.google.android.c2dm.intent.RECEIVE" /&gt;
    347                 &lt;action android:name="com.google.android.c2dm.intent.REGISTRATION" /&gt;
    348                 &lt;category android:name="com.example.gcm" /&gt;
    349             &lt;/intent-filter&gt;
    350         &lt;/receiver&gt;
    351         &lt;service android:name=".MyIntentService" /&gt;
    352     &lt;/application&gt;
    353 
    354 &lt;/manifest&gt;
    355 </pre>
    356 <h3 id="registering">Registering for GCM</h3>
    357 
    358 <p>An Android application needs to register with GCM servers before it can receive messages. To register, the application sends an Intent
    359 (<code>com.google.android.c2dm.intent.REGISTER</code>), with 2 extra parameters:
    360 </p>
    361 
    362 <ul>
    363   <li><code>sender</code> is the project ID of the account authorized to send messages
    364 to the Android application. </li>
    365   <li><code>app</code> is the Android application's ID, set with a <code>PendingIntent</code> to
    366 allow the registration service to extract Android application information. </li>
    367 </ul>
    368 
    369 <p>For example:</p>
    370 
    371 <pre class="prettyprint pretty-java">Intent registrationIntent = new Intent(&quot;com.google.android.c2dm.intent.REGISTER&quot;);
    372 // sets the app name in the intent
    373 registrationIntent.putExtra(&quot;app&quot;, PendingIntent.getBroadcast(this, 0, new Intent(), 0));
    374 registrationIntent.putExtra(&quot;sender&quot;, senderID);
    375 startService(registrationIntent);</pre>
    376 
    377 <p>This intent will be asynchronously sent to the GCM server, and the response will be delivered to
    378 the application as a <code>com.google.android.c2dm.intent.REGISTRATION</code> intent containing
    379 the registration ID assigned to the Android application running on that particular device.</p>
    380 
    381 <p>Registration is not complete until the Android application sends the registration ID
    382 to the 3rd-party application server, which in turn will use the registration ID to send
    383 messages to the application.</p>
    384 
    385 <h3 id="unregistering">Unregistering from GCM</h3>
    386 
    387 <p>To unregister from GCM, do the following:</p>
    388 
    389 <pre class="prettyprint pretty-java">Intent unregIntent = new Intent(&quot;com.google.android.c2dm.intent.UNREGISTER&quot;);
    390 unregIntent.putExtra(&quot;app&quot;, PendingIntent.getBroadcast(this, 0, new Intent(), 0));
    391 startService(unregIntent);
    392 </pre>
    393 
    394 <p>Similar to the registration request, this intent is sent asynchronously, and the response comes as a <code>com.google.android.c2dm.intent.REGISTRATION</code> intent.
    395 
    396 
    397 <h3 id="handling_intents">Handling Intents sent by GCM</h3>
    398 
    399 <p>As discussed in <a href="#manifest">Creating the Manifest</a>, the manifest
    400 defines a broadcast receiver for the <code>com.google.android.c2dm.intent.REGISTRATION</code> and <code>com.google.android.c2dm.intent.RECEIVE</code> intents.
    401 These <a href="{@docRoot}guide/components/intents-filters.html">intents</a> are sent by GCM to indicate that a device was registered (or unregistered), or to deliver messages, respectively.</p>
    402 
    403 <p>Handling these intents might require I/O operations (such as network calls to the 3rd party server), and 
    404 such operations should not be done in the receiver's <code>onReceive()</code> method.
    405 You may be tempted to spawn a new thread directly, but there are no guarantees that the process will run long enough for the thread to finish the work.  
    406 Thus the recommended way to handle the intents is to delegate them to a service, such as an {@link android.app.IntentService}. 
    407 For example:</p>
    408 
    409 
    410 <pre class="prettyprint pretty-java">
    411 public class MyBroadcastReceiver extends BroadcastReceiver {
    412 
    413     &#64;Override
    414     public final void onReceive(Context context, Intent intent) {
    415         MyIntentService.runIntentInService(context, intent);
    416         setResult(Activity.RESULT_OK, null, null);
    417     }
    418 }
    419 </pre>
    420 
    421 <p>Then in <code>MyIntentService</code>:</p>
    422 <pre class="prettyprint pretty-java">
    423 public class MyIntentService extends IntentService {
    424 
    425     private static PowerManager.WakeLock sWakeLock;
    426     private static final Object LOCK = MyIntentService.class;
    427     
    428     static void runIntentInService(Context context, Intent intent) {
    429         synchronized(LOCK) {
    430             if (sWakeLock == null) {
    431                 PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
    432                 sWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "my_wakelock");
    433             }
    434         }
    435         sWakeLock.acquire();
    436         intent.setClassName(context, MyIntentService.class.getName());
    437         context.startService(intent);
    438     }
    439     
    440     &#64;Override
    441     public final void onHandleIntent(Intent intent) {
    442         try {
    443             String action = intent.getAction();
    444             if (action.equals("com.google.android.c2dm.intent.REGISTRATION")) {
    445                 handleRegistration(intent);
    446             } else if (action.equals("com.google.android.c2dm.intent.RECEIVE")) {
    447                 handleMessage(intent);
    448             }
    449         } finally {
    450             synchronized(LOCK) {
    451                 sWakeLock.release();
    452             }
    453         }
    454     }
    455 }
    456 </pre>
    457 
    458 <p class="note"><strong>Note:</strong> your application must acquire a wake lock before starting the service&mdash;otherwise the device could be put to sleep before the service is started.</p>
    459 
    460 <h4 id="handling_reg">Handling Registration Results</h4>
    461 
    462 <p>When a <code>com.google.android.c2dm.intent.REGISTRATION</code> intent is received, it could potentially contain 3 extras: <code>registration_id</code>, <code>error</code>, and <code>unregistered</code>.
    463 
    464 <p>When a registration succeeds, <code>registration_id</code> contains the registration ID and the other extras are not set. 
    465 The application must ensure that the 3rd-party server receives the registration ID. It may do so by saving the registration ID and sending it to the server. 
    466 If the network is down or there are errors, the application should retry sending the registration ID when the network is up again or the next time it starts.</p>
    467 
    468 <p class="note"><strong>Note:</strong> Although the <code>com.google.android.c2dm.intent.REGISTRATION</code> intent is typically received after a request was made by the application, 
    469 Google may periodically refresh the registration ID. So the application must be prepared to handle it at any time.</p>
    470 
    471 <p>When an unregistration succeeds, only the <code>unregistered</code> extra is set, and similar to the registration workflow, 
    472 the application must contact the 3rd-party server to remove the registration ID (note that the registration ID is not available in the intent, 
    473 but the application should have saved the registration ID when it got it).<p>
    474 
    475 <p>If the application request (be it register or unregister) fails, the <code>error</code> will be set with an error code, and the other extras will not be set. 
    476 
    477 Here are the possible error codes:</p>
    478 
    479 <table>
    480   <tr>
    481     <th>Error Code</th>
    482     <th>Description</th>
    483   </tr>
    484   <tr>
    485     <td><code>SERVICE_NOT_AVAILABLE</code></td>
    486     <td>The device can't read the response, or there was a 500/503 from the
    487 server that can be retried later. The Android application should use exponential back-off and retry. See <a href="adv.html#retry">Advanced Topics</a> for more information. </td>
    488   </tr>
    489   <tr>
    490     <td><code>ACCOUNT_MISSING</code></td>
    491     <td>There is no Google account on the phone.  The Android application should ask the
    492 user to open the account manager and add a Google account. Fix on the device
    493 side.</td>
    494   </tr>
    495   <tr>
    496     <td><code>AUTHENTICATION_FAILED</code></td>
    497     <td>Bad Google Account password. The Android application should ask the user to enter his/her Google Account
    498 password, and let the user retry manually later. Fix on the device side.</td>
    499   </tr>
    500   <tr>
    501     <td><code>INVALID_SENDER</code></td>
    502     <td>The sender account is not recognized. This must be fixed on the Android application side. The developer must fix the application to provide the right <code>sender</code> extra in the <code>com.google.android.c2dm.intent.REGISTER</code> intent.</td>
    503   </tr>
    504   <tr>
    505     <td><code>PHONE_REGISTRATION_ERROR</code></td>
    506     <td> Incorrect phone registration with Google. This
    507 phone doesn't currently support GCM.</td>
    508   </tr>
    509   <tr>
    510     <td><code>INVALID_PARAMETERS</code></td>
    511     <td>The  request sent by the phone does not contain the expected parameters. This phone doesn't currently support GCM.</td>
    512   </tr>
    513 </table>
    514 
    515 
    516 
    517 
    518 <p>Here's an example on how to handle the registration in the <code>MyIntentService</code> example:</p>
    519 
    520 <pre class="prettyprint pretty-java">
    521 private void handleRegistration(Intent intent) {
    522     String registrationId = intent.getStringExtra("registration_id");
    523     String error = intent.getStringExtra("error");
    524     String unregistered = intent.getStringExtra("unregistered");       
    525     // registration succeeded
    526     if (registrationId != null) {
    527         // store registration ID on shared preferences
    528         // notify 3rd-party server about the registered ID
    529     }
    530         
    531     // unregistration succeeded
    532     if (unregistered != null) {
    533         // get old registration ID from shared preferences
    534         // notify 3rd-party server about the unregistered ID
    535     } 
    536         
    537     // last operation (registration or unregistration) returned an error;
    538     if (error != null) {
    539         if ("SERVICE_NOT_AVAILABLE".equals(error)) {
    540            // optionally retry using exponential back-off
    541            // (see <a href="adv.html#retry">Advanced Topics</a>)
    542         } else {
    543             // Unrecoverable error, log it
    544             Log.i(TAG, "Received error: " + error);
    545         }
    546     }
    547 }</pre>
    548 
    549 <h4 id="received_data">Handling Received Data</h4>
    550 
    551 <p>The <code>com.google.android.c2dm.intent.RECEIVE</code> intent is used by GCM to 
    552 deliver the messages sent by the 3rd-party server to the application running in the device.
    553 If the server included key-pair values in the <code>data</code> parameter, they are available as 
    554 extras in this intent, with the keys being the extra names. GCM also includes an  extra called 
    555 <code>from</code> which contains the sender ID as an string, and another called <code>collapse_key</code> containing the collapse key (when in use).
    556 
    557 <p>Here is an example, again using the <code>MyIntentReceiver</code> class:</p>
    558 
    559 <pre class="prettyprint pretty-java">
    560 private void handleMessage(Intent intent) {
    561     // server sent 2 key-value pairs, score and time
    562     String score = intent.getExtra("score");
    563     String time = intent.getExtra("time");
    564     // generates a system notification to display the score and time
    565 }</pre>
    566 
    567 <h3 id="testing">Developing and Testing Your Android Applications</h3>
    568 
    569 <p>Here are some guidelines for developing and testing an Android application
    570 that uses the GCM feature:</p>
    571 
    572 <ul>
    573   <li>To develop and test your Android applications, you need to run and debug the
    574 applications on an Android 2.2 system image that includes the necessary
    575 underlying Google services. </li>
    576   <li>To develop and debug on an actual device, you need a device running an
    577 Android 2.2 system image that includes the Google Play Store application. </li>
    578   <li>To develop and test on the Android Emulator, you need to download the
    579 Android 2.2 version of the Google APIs Add-On into your SDK using the <em>Android
    580 SDK and AVD Manager</em>. Specifically, you need to download the component named
    581 &quot;Google APIs by Google Inc, Android API 8&quot;. Then, you need to set up
    582 an AVD that uses that system image. </li>
    583   <li>If the GCM feature is critical to the Android application's function, be sure to
    584 set <code>android:minSdkVersion=&quot;8&quot;</code> in the manifest. This
    585 ensures that the Android application cannot be installed in an environment in which it
    586 could not run properly. </li>
    587 </ul>
    588 
    589 <h2 id="server">Role of the 3rd-party Application Server</h2>
    590 
    591 <p>Before you can write client Android applications that use the GCM feature, you must
    592 have an  application server that meets the following criteria:</p>
    593 
    594 <ul>
    595   <li>Able to communicate with your client.</li>
    596   <li>Able to  fire off HTTPS requests to the GCM server.</li>
    597   <li>Able to handle requests and resend then as needed, using <a href="http://en.wikipedia.org/wiki/Exponential_backoff">exponential back-off.</a></li>
    598   <li>Able to store the API key and client registration IDs. The
    599 API key is included in the header of POST requests that send
    600 messages.</li>
    601 </ul>
    602 
    603 <h3 id="send-msg">Sending Messages</h3>
    604 <p>This section describes how the 3rd-party application server sends messages to one or more mobile devices. Note the following:</p>
    605 <ul>
    606   <li>A 3rd-party application server can either send messages to a single device or to multiple devices. A message sent to multiple devices simultaneously is called a <em>multicast message</em>.</li>
    607   
    608   <li>You have 2 choices in how you construct requests and responses: plain text or JSON.</li>
    609   <li>However, to send multicast messages, you must use JSON. Plain text will not work.</li>
    610 </ul>
    611 <p>Before the 3rd-party application server can send a  message to an
    612   Android application, it must have received a registration ID from it.</p>
    613 <h4 id="request">Request format</h4>
    614 <p>To send a  message, the application server issues a POST request to <code>https://android.googleapis.com/gcm/send</code>.</p>
    615 <p>A  message request is made of 2 parts: HTTP header and HTTP body.</p>
    616 
    617 <p>The HTTP header must contain the following headers:</p>
    618 <ul>
    619   <li><code>Authorization</code>: key=YOUR_API_KEY</li>
    620   <li><code>Content-Type</code>: <code>application/json</code> for JSON; <code>application/x-www-form-urlencoded;charset=UTF-8</code> for plain text.
    621   </li>
    622 </ul>
    623 
    624 <p>For example:
    625 </p>
    626 <pre>Content-Type:application/json
    627 Authorization:key=AIzaSyB-1uEai2WiUapxCs2Q0GZYzPu7Udno5aA
    628 
    629 {
    630   "registration_ids" : ["APA91bHun4MxP5egoKMwt2KZFBaFUH-1RYqx..."],
    631   "data" : {
    632     ...
    633   },
    634 }</pre>
    635 <p class="note">
    636   <p><strong>Note:</strong> If <code>Content-Type</code> is omitted, the format is assumed to be plain text.</p>
    637 </p>
    638 
    639 <p>The HTTP body content depends on whether you're using JSON or plain text. For JSON, it must contain a string representing a JSON object with the following fields:</p>
    640 <table>
    641   <tr>
    642     <th>Field</th>
    643     <th>Description</th>
    644   </tr>
    645   <tr>
    646     <td><code>registration_ids</code></td>
    647     <td>A string array with 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). Required.</td>
    648   </tr>
    649   <tr>
    650     <td><code>collapse_key</code></td>
    651     <td>An arbitrary string (such as &quot;Updates Available&quot;) that is used to collapse a group of like messages
    652 when the device is offline, so that only the last message gets sent to the
    653 client. This is intended to avoid sending too many messages to the phone when it
    654 comes back online. Note that since there is no guarantee of the order in which
    655 messages get sent, the &quot;last&quot; message may not actually be the last
    656 message sent by the application server. See <a href="adv.html#collapsible">Advanced Topics</a> for more discussion of this topic. Optional.</td>
    657   </tr>
    658   <tr>
    659     <td><code>data</code></td>
    660     <td>A JSON object whose fields represents the key-value pairs of the message's payload data. If present, the payload data it will be
    661 included in the Intent as application data, with the key being the extra's name. For instance, <code>"data":{"score":"3x1"}</code> would result in an intent extra named <code>score</code> whose value is the string <code>3x1</code>. 
    662 
    663 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 (<code>from</code> or any word starting with <code>google.</code>). To complicate things slightly, there are some reserved words (such as <code>collapse_key</code>) that are technically allowed in payload data. However, if the request also contains the word, the value in the request will overwrite the value in the payload data. Hence using words that are defined as field names in this table is not recommended, even in cases where they are technically allowed. Optional.</td>
    664 
    665 
    666   </tr>
    667   <tr>
    668     <td><code>delay_while_idle</code></td>
    669     <td>If included, indicates that the message should not be sent immediately
    670 if the device is idle. The server will wait for the device to become active, and
    671 then only the last message for each <code>collapse_key</code> value will be
    672 sent. Optional. The default value is <code>false</code>, and must be a JSON boolean.</td>
    673   </tr>
    674   <tr>
    675     <td><code>time_to_live</code></td>
    676     <td>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).</td>
    677   </tr>
    678 </table>
    679 
    680 <p>If you are using plain text instead of JSON, the message fields must be set as HTTP parameters sent in the body, and their syntax is slightly different, as described below:
    681 <table>
    682   <tr>
    683     <th>Field</th>
    684     <th>Description</th>
    685   </tr>
    686   <tr>
    687     <td><code>registration_id</code></td>
    688     <td>Must contain the registration ID of the single device receiving the message. Required.</td>
    689   </tr>
    690   <tr>
    691     <td><code>collapse_key</code></td>
    692     <td>Same as JSON (see previous table). Optional.</td>
    693   </tr>
    694   <tr>
    695     <td><code>data.&lt;key&gt;</code></td>
    696 
    697     <td>Payload data, expressed as parameters prefixed with <code>data.</code> and suffixed as the key. For instance, a parameter of <code>data.score=3x1</code> would result in an intent extra named <code>score</code> whose value is the string <code>3x1</code>. 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 (<code>from</code> or any word starting with 
    698 <code>google.</code>). To complicate things slightly, there are some reserved words (such as <code>collapse_key</code>) that are technically allowed in payload data. However, if the request also contains the word, the value in the request will overwrite the value in the payload data. Hence using words that are defined as field names in this table is not recommended, even in cases where they are technically allowed. Optional.</td>
    699 
    700   </tr>
    701   <tr>
    702     <td><code>delay_while_idle</code></td>
    703     <td>Should be represented as <code>1</code> or <code>true</code> for <code>true</code>, anything else for <code>false</code>. Optional. The default value is <code>false</code>.</td>
    704   </tr>
    705   <tr>
    706     <td><code>time_to_live</code></td>
    707     <td>Same as JSON (see previous table). Optional.</td>
    708   </tr>
    709 </table>
    710 
    711 
    712 
    713   <h4 id="example-requests">Example requests</h4>
    714   <p>Here is the smallest possible request (a message without any parameters and just one recipient) using JSON:</p>
    715   <pre class="prettyprint pretty-json">{ &quot;registration_ids&quot;: [ &quot;42&quot; ] }</pre>
    716   
    717   <p>And here the same example using plain text:</p>
    718   <pre class="prettyprint">registration_id=42</pre>
    719   
    720   <p> Here is a message with a payload and 6 recipients:</p>
    721   <pre class="prettyprint pretty-HTML">{ "data": {
    722     "score": "5x1",
    723     "time": "15:10"
    724   },
    725   "registration_ids": ["4", "8", "15", "16", "23", "42"]
    726 }</pre>
    727   <p>Here is a message with all optional fields set and 6 recipients:</p>
    728   <pre class="prettyprint pretty-json">{ "collapse_key": "score_update",
    729   "time_to_live": 108,
    730   "delay_while_idle": true,
    731   "data": {
    732     "score": "4x8",
    733     "time": "15:16.2342"
    734   },
    735   "registration_ids":["4", "8", "15", "16", "23", "42"]
    736 }</pre>
    737   <p>And here is the same message using plain-text format (but just 1 recipient):  </p>
    738   
    739   <pre class="prettyprint">collapse_key=score_update&amp;time_to_live=108&amp;delay_while_idle=1&amp;data.score=4x8&amp;data.time=15:16.2342&amp;registration_id=42
    740   </pre>
    741 
    742   <p class="note"><strong>Note:</strong> If your organization has a firewall that restricts the traffic to or from the Internet, you'll need to configure it to allow connectivity with GCM. The ports to open are: 5228, 5229, and 5230. GCM typically only uses 5228, but it sometimes uses 5229 and 5230.
    743 GCM doesn't provide specific IPs. It changes IPs frequently. We recommend against using ACLs but if you must use them, take a broad approach such as the method suggested in <a href="http://support.google.com/code/bin/answer.py?hl=en&answer=62464">this support link</a>.
    744 </p>
    745 
    746 <h4 id="response">Response format</h4>
    747 
    748 <p>There are two possible outcomes when trying to send a message:</p>
    749 <ul>
    750   <li>The message is processed successfully.</li>
    751   <li>The GCM server rejects the request.</li>
    752 </ul>
    753 
    754 <p>When the messge 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, 
    755 the HTTP response contains a non-200 status code (such as 400, 401, or 503).</p>
    756 
    757 <p>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.</p>
    758 <table border=1>
    759   <tr>
    760     <th>Response</th>
    761     <th>Description</th>
    762   </tr>
    763   <tr>
    764     <td>200</td>
    765     <td>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 <a href="#success">Interpreting a success response</a> for more details.</td>
    766   </tr>
    767   <tr>
    768     <td>400</td>
    769     <td><span id="internal-source-marker_0.2">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.</td>
    770   </tr>
    771   <tr>
    772     <td>401</td>
    773     <td>There was an error authenticating the sender account. <a href="#auth_error">Troubleshoot</a></td>
    774   </tr>
    775   <tr>
    776     <td>5xx</td>
    777     <td>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 <code>Retry-After</code> header included in the response. Application servers must implement exponential back-off. <a href="#internal_error">Troubleshoot</a></td>
    778   </tr>
    779 </table>
    780 
    781 <h4 id="success">Interpreting a success response</h4>
    782 <p>When a JSON request is successful (HTTP status code 200), the response body contains a JSON object with the following fields:</p>
    783 <table>
    784   <tr>
    785     <th>Field</th>
    786     <th>Description</th>
    787   </tr>
    788   <tr>
    789     <td><code>multicast_id</code></td>
    790     <td>Unique ID (number) identifying the multicast message.</td>
    791   </tr>
    792   <tr>
    793     <td><code>success</code></td>
    794     <td>Number of messages that were processed without an error.</td>
    795   </tr>
    796   <tr>
    797     <td><code>failure</code></td>
    798     <td>Number of messages that could not be processed.</td>
    799   </tr>
    800   <tr>
    801     <td><code>canonical_ids</code></td>
    802     <td>Number of results that contain a canonical registration ID. See <a href="adv.html#canonical">Advanced Topics</a> for more discussion of this topic.</td>
    803   </tr>
    804   <tr>
    805     <td><code>results</code></td>
    806     <td>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) and they can have these fields:<br>
    807       <ul>
    808         <li><code>message_id</code>: String representing the message when it was successfully processed.</li>
    809         <li><code>registration_id</code>: If set,  means that GCM processed the message but it has another canonical registration ID for that device, so sender should replace the IDs on future requests (otherwise they might be rejected). This field is never set if there is an error in the request.<br />
    810         </li>
    811         <li><code>error</code>: String describing an error that occurred while processing the message for that recipient. The possible values are the same as documented in the above table, plus &quot;Unavailable&quot;  (meaning GCM servers were busy and could not process the message for that  particular recipient, so it could be retried).</li>
    812     </ul></td>
    813   </tr>
    814 </table>
    815 <p>If the value of <code>failure</code> and <code>canonical_ids</code> 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:</p>
    816 <ul>
    817   <li>If <code>message_id</code> is set, check for <code>registration_id</code>:
    818     <ul>
    819       <li>If <code>registration_id</code> 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</code> passed in the request (using the same index).</li>
    820     </ul>
    821   </li>
    822   <li>Otherwise, get the value of <code>error</code>:
    823     <ul>
    824       <li>If it is <code>Unavailable</code>, you could retry to send it in another request.</li>
    825       <li>If it is <code>NotRegistered</code>, 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 <code>com.google.android.c2dm.intent.RECEIVE</code> intents.</li>
    826       <li>Otherwise, there is something wrong in the registration ID passed in the request; it is probably a non-recoverable error that will also require removing the registration from the server database. See <a href="#error_codes">Interpreting an error response</a> for all possible error values.</li>
    827     </ul>
    828   </li>
    829 </ul>
    830 
    831 <p>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.
    832 The first line is always available and its content is either <code>id=<em>ID of sent message</em></code> or <code>Error=<em>GCM error code</em></code>. The second line, if available, 
    833 has the format of <code>registration_id=<em>canonical ID</em></code>. 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:</p>
    834 <ul>
    835   <li>If first line starts with <code>id</code>, check second line:
    836     <ul>
    837       <li>If second line starts with <code>registration_id</code>, gets its value and replace the registration IDs in your server database.</li>
    838     </ul>
    839   </li>
    840   <li>Otherwise, get the value of <code>Error</code>:
    841     <ul>
    842       <li>If it is <code>NotRegistered</code>, remove the registration ID from your server database.</li>
    843       <li>Otherwise, there is probably a non-recoverable error (<strong>Note: </strong>Plain-text requests will never return <code>Unavailable</code> as the error code, they would have returned a 500 HTTP status instead).</li>
    844     </ul>
    845   </li>
    846 </ul>
    847 
    848 <h4 id="error_codes">Interpreting an error response</h4>
    849 <p>Here are the recommendations for handling the different types of error that might occur when trying to send a message to a device:</p>
    850 
    851 <dl>
    852 <dt id="missing_reg"><strong>Missing Registration ID</strong></dt>
    853 <dd>Check that the request contains a registration ID (either in the <code>registration_id</code> parameter in a plain text message, or in the <code>registration_ids</code> field in JSON). 
    854 <br/>Happens when error code is <code>MissingRegistration</code>.</dd>
    855 
    856 <dt id="invalid_reg"><strong>Invalid Registration ID</strong></dt>
    857 <dd>Check the formatting of the registration ID that you pass to the server. Make sure it matches the registration ID the phone receives in the <code>com.google.android.c2dm.intent.REGISTRATION</code> intent and that you're not truncating it or adding additional characters. 
    858 <br/>Happens when error code is <code>InvalidRegistration</code>.</dd>
    859 
    860 <dt id="mismatched_sender"><strong>Mismatched Sender</strong></dt>
    861 <dd>A registration ID is tied to a certain group of senders. When an application registers for GCM usage, it must specify which senders are allowed to send messages. Make sure you're using one of those when trying to send messages to the device. If you switch to a different sender, the existing registration IDs won't work. 
    862 Happens when error code is <code>MismatchSenderId</code>.</dd>
    863 
    864 <dt id="unreg_device"><strong>Unregistered Device</strong></dt>
    865 <dd>An existing registration ID may cease to be valid in a number of scenarios, including:
    866 <ul>
    867   <li>If the application manually unregisters by issuing a <span class="prettyprint pretty-java"><code>com.google.android.c2dm.intent.UNREGISTER</code></span><code> </code>intent.</li>
    868   <li>If the application is automatically unregistered, which can happen (but is not guaranteed) if the user uninstalls the application.</li>
    869   <li>If the registration ID expires. Google might decide to refresh registration IDs. </li>
    870   <li>If the application is updated but the new version does not have a broadcast receiver configured to receive <code>com.google.android.c2dm.intent.RECEIVE</code> intents.</li>
    871 </ul>
    872 For all these cases, you should remove this registration ID from the 3rd-party server and stop using it to send 
    873 messages. 
    874 <br/>Happens when error code is <code>NotRegistered</code>.</dd>
    875 
    876 <dt id="big_msg"><strong>Message Too Big</strong></dt>
    877   <dd>The total size of the payload data that is included in a message can't exceed 4096 bytes. Note that this includes both the size of the keys as well as the values. 
    878 <br/>Happens when error code is <code>MessageTooBig</code>.</dd>
    879 
    880 <dt id="invalid_datakey"><strong>Invalid Data Key</strong></dt>
    881 <dd>The payload data contains a key (such as <code>from</code> or any value prefixed by <code>google.</code>) that is used internally by GCM in the  <code>com.google.android.c2dm.intent.RECEIVE</code> Intent and cannot be used. Note that some words (such as <code>collapse_key</code>) are also used by GCM but are allowed in the payload, in which case the payload value will be overridden by the GCM value. 
    882 <br />
    883 Happens when the error code is <code>InvalidDataKey</code>.</dd>
    884 
    885 <dt id="ttl_error"><strong>Invalid Time To Live</strong></dt>
    886   <dd>The value for the Time to Live field must be an integer representing a duration in seconds between 0 and 2,419,200 (4 weeks). Happens when error code is <code>InvalidTtl</code>.
    887 </dd>
    888 
    889   <dt id="auth_error"><strong>Authentication Error</strong></dt>
    890   <dd>The sender account that you're trying to use to send a message couldn't be authenticated. Possible causes are: <ul>
    891 <li>Authorization header missing or with invalid syntax.</li>
    892 <li>Invalid project ID sent as key.</li>
    893 <li>Key valid but with GCM service disabled.</li>
    894 <li>Request originated from a server not whitelisted in the Server Key IPs.</li>
    895 
    896 </ul>
    897 Check that the token you're sending inside the <code>Authorization</code> header is the correct API key associated with your project. You can check the validity of your API key by running the following command:<br/>
    898 
    899 <pre># api_key=YOUR_API_KEY
    900 
    901 # curl --header "Authorization: key=$api_key" --header Content-Type:"application/json" https://android.googleapis.com/gcm/send  -d "{\"registration_ids\":[\"ABC\"]}"</pre>
    902 
    903 
    904 If you receive a 401 HTTP status code, your API key is not valid. Otherwise you should see something like this:<br/>
    905 
    906 <pre>
    907 {"multicast_id":6782339717028231855,"success":0,"failure":1,"canonical_ids":0,"results":[{"error":"InvalidRegistration"}]}
    908 </pre>
    909 If you want to confirm the validity of a registration ID, you can do so by replacing "ABC" with the registration ID.
    910 <br/>
    911 Happens when the HTTP status code is 401.
    912 
    913   <dt id="timeout"><strong>Timeout</strong></dt>
    914 
    915 <dd>The server couldn't process the request in time. You should retry the
    916 same request, but you MUST obey the following requirements:
    917 
    918 <ul>
    919 
    920 <li>Honor the <code>Retry-After</code> header if it's included in the response from the GCM server.</li>
    921         
    922         
    923 <li>Implement exponential back-off in your retry mechanism. This means an
    924 exponentially increasing delay after each failed retry (e.g. if you waited one
    925 second before the first retry, wait at least two second before the next one,
    926 then 4 seconds and so on). If you're sending multiple messages, delay each one
    927 independently by an additional random amount to avoid issuing a new request for
    928 all messages at the same time.</li>
    929     
    930 
    931 Senders that cause problems risk being blacklisted. 
    932 <br />
    933 Happens when the HTTP status code is between 501 and 599, or when the <code>error</code> field of a JSON object in the results array is <code>Unavailable</code>.
    934 </dd>
    935 
    936 <dt id="internal_error"><strong>Internal Server Error</strong></dt>
    937 
    938 <dd>
    939 The server encountered an error while trying to process the request. You
    940 could retry the same request (obeying the requirements listed in the <a href="#timeout">Timeout</a>
    941 section), but if the error persists, please report the problem in the <a href="https://groups.google.com/forum/?fromgroups#!forum/android-gcm">android-gcm group</a>.
    942 <br />
    943 Happens when the HTTP status code is 500, or when the <code>error</code> field of a JSON
    944 object in the results array is <code>InternalServerError</code>.
    945 </dd>
    946 
    947 
    948 </dl>
    949 <h4>Example responses</h4>
    950 <p>This section shows a few examples of responses indicating messages that were processed successfully. See <a href="#example-requests">Example requests</a> for the requests these responses are based on.</p>
    951 <p> Here is a simple case of a JSON message successfully sent to one recipient without canonical IDs in the response:</p>
    952 <pre class="prettyprint pretty-json">{ "multicast_id": 108,
    953   "success": 1,
    954   "failure": 0,
    955   "canonical_ids": 0,
    956   "results": [
    957     { "message_id": "1:08" }
    958   ]
    959 }</pre>
    960 
    961 <p>Or if the request was in plain-text format:</p>
    962 <pre class="prettyprint">id=1:08
    963 </pre>
    964 
    965 <p>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:</p>
    966 <pre class="prettyprint pretty-json">{ "multicast_id": 216,
    967   "success": 3,
    968   "failure": 3,
    969   "canonical_ids": 1,
    970   "results": [
    971     { "message_id": "1:0408" },
    972     { "error": "Unavailable" },
    973     { "error": "InvalidRegistration" },
    974     { "message_id": "1:1516" },
    975     { "message_id": "1:2342", "registration_id": "32" },
    976     { "error": "NotRegistered"}
    977   ]
    978 }
    979 </pre>
    980 <p> In this example:</p>
    981 <ul>
    982   <li>First message: success, not required.</li>
    983   <li>Second message: should be resent (to registration ID 8).</li>
    984   <li>Third message: had an unrecoverable error (maybe the value got corrupted in the database).</li>
    985   <li>Fourth message: success, nothing required.</li>
    986   <li>Fifth message: success, but the registration ID should be updated in the server database (from 23 to 32).</li>
    987   <li>Sixth message: registration ID (42) should be removed from the server database because the application was uninstalled from the device.</li>
    988 </ul>
    989 <p>Or if just the 4th message above was sent using plain-text format:</p>
    990 <pre class="prettyprint">Error=InvalidRegistration
    991 </pre>
    992 <p>If the 5th message above was also sent using plain-text format:</p>
    993 <pre class="prettyprint">id=1:2342
    994 registration_id=32
    995 </pre>
    996 
    997 
    998 <h3 id="stats">Viewing statistics</h3>
    999 
   1000 <p>To view  statistics and any error messages for your GCM applications:</p>
   1001 <ol>
   1002   <li> Go to the <code><a href="http://play.google.com/apps/publish">Android Developer Console</a></code>.</li>
   1003   <li>Login with your developer account. 
   1004   <p>You will see a page that has a list of all of your apps.</p></li>
   1005   <li> Click on the &quot;statistics&quot; link next to the app for which you want to view GCM stats. 
   1006   <p>Now you are on the statistics page.</p> </li>
   1007   <li>Go to the drop-down menu and select the GCM metric you want to view. 
   1008   </li>
   1009 </ol>
   1010 <p class="note"><strong>Note:</strong> Stats on the Google API Console are not enabled for GCM. You must use the <a href="http://play.google.com/apps/publish">Android Developer Console</a>.</p>
   1011 
   1012 <h2 id="example">Examples</h2>
   1013 <p>See the <a href="demo.html">GCM Demo Application</a> document.</p>
   1014 
   1015