1page.title=User Notifications
2@jd:body
3
4<div id="qv-wrapper">
5<div id="qv">
6
7<h2>Quickview</h2>
8
9<ul>
10<li>Learn how to send a single message to multiple devices owned by a single user.</li>
11</ul>
12
13
14<h2>In this document</h2>
15
16<ol class="toc">
17  <li><a href="#gen-server">Generate a Notification Key on the Server</a></li>
18  <li><a href="#gen-client">Generate a Notification Key on the Client</a></li>
19  <li><a href="#add">Add Registration IDs</a></li>
20  <li><a href="#remove">Remove Registration IDs</a></li>
21  <li><a href="#upstream">Send Upstream Messages</a></li>
22  <li><a href="#response">Response Formats</a>
23    <ol class="toc">
24      <li><a href="#response-create">Create/add/remove operations</a>
25      <li><a href="#response-send">Send operations</a>
26    </ol>
27  </li>
28</ol>
29
30<h2>See Also</h2>
31
32<ol class="toc">
33<li><a href="{@docRoot}google/gcm/gs.html">Getting Started</a></li>
34</ol>
35
36</div>
37</div>
38
39<p>With user notifications, 3rd-party app servers can send a single message to
40multiple instance of an app running on devices owned by a single user. This feature
41is called <em>user notifications</em>. User notifications make it possible for every
42app instance that a user owns to reflect the latest messaging state. For example:</p>
43
44  <ul>
45  <li>If a message has been handled on one device, the GCM message on the other
46devices are dismissed. For example, if a user has handled a calendar notification
47on one device, the notification will go away on the user's other devices.</li>
48
49  <li>If a message has not been delivered yet to a device and but it has been handled,
50the GCM server removes it from the unsent queue for the other devices.</li>
51
52  <li>Likewise, a device can send messages to the {@code notification_key}, which
53is the token that GCM uses to fan out notifications to all devices whose
54registration IDs are associated with the key.</li>
55</ul>
56
57<p>The way this works is that during registration, the 3rd-party server requests
58a {@code notification_key}. The {@code notification_key} maps a particular user
59to all of the user's associated registration IDs (a regID represents a particular
60Android application running on a particular device). Then instead of sending one
61message to one regID at a time, the 3rd-party server can send a message to to the
62{@code notification_key}, which then sends the message to all of the user's regIDs.</p>
63
64<p class="note"><strong>Note:</strong> A notification dismissal message is like any
65other upstream message, meaning that it will be delivered to the other devices that
66belong to the specified {@code notification_key}. You should design your app to
67handle cases where the app receives a dismissal message, but has not yet displayed
68the notification that is being dismissed. You can solve this by caching the dismissal
69and then reconciling it with the corresponding notification.
70</p>
71
72<p>You can use this feature with either the <a href="ccs.html">XMPP</a> (CCS) or
73<a href="http.html">HTTP</a> connection server.</p>
74
75<p>You can generate notification keys in two different ways: on the server, and on
76the client, if the user has a Google account. All of the associated registration IDs
77can be mapped to a single user.</p>
78
79<p>The examples below show you how to perform generate/add/remove operations,
80and how to send upstream messages. For generate/add/remove operations, the
81message body is JSON.</p>
82
83<h2 id="gen-server">Generate a Notification Key on the Server</h2>
84
85<p>To generate a notification key on the server, you create a new
86<code>notification_key</code> and map it to a
87<code>notification_key_name</code>.</p>
88
89<p>This example shows how to create a new <code>notification_key</code> for a
90<code>notification_key_name</code> called <code>appUser-Chris</code>.
91The {@code notification_key_name} is a name or identifier (it can be a username for
92a 3rd-party app) that is unique to a given user. It is used by third parties to
93group together registration IDs for a single user. Note that <code>notification_key_name</code>
94and <code>notification_key</code> are unique to a group of registration IDs. It is also
95important that <code>notification_key_name</code> be uniquely named per app in case
96you have multiple apps for the same project ID. This ensures that notifications
97only go to the intended target app.</p>
98
99
100<p>A create operation returns a token (<code>notification_key</code>). Third parties
101must save this token (as well as its mapping to the <code>notification_key_name</code>)
102to use in subsequent operations:</p>
103
104<pre>request:
105{
106   &quot;operation&quot;: &quot;create&quot;,
107   &quot;notification_key_name&quot;: &quot;appUser-Chris&quot;,
108   &quot;registration_ids&quot;: [&quot;4&quot;, &quot;8&quot;, &quot;15&quot;, &quot;16&quot;, &quot;23&quot;, &quot;42&quot;]
109}</pre>
110
111<h3 id="request-server">Request format</h3>
112
113<p>To send a message in cases where your notification key is generated on the server,
114the application server issues a POST request to
115<code>https://android.googleapis.com/gcm/notification</code>.</p>
116
117<p>Here is the HTTP request header you should use for all server side create/add/remove operations:</p>
118
119<pre>content-type: "application/json"
120Header : "project_id": &lt;projectID&gt;
121Header: "Authorization", "key=API_KEY"
122</pre>
123
124
125<h2 id="gen-client">Generate a Notification Key on the Client</h2>
126
127<p>Generating a notification key on the client is useful for cases where a server is unavailable.
128To generate a notification key on the client, the device must have at least one
129Google account. Note that the process for generating a notification key on the client is significantly
130different from the server process described above.</p>
131
132<p>To generate a notification key on the client:</p>
133
134<ol>
135  <li>Open your project in the <a href="https://cloud.google.com/console">Google Developers Console</a>.</li>
136  <li>Click <strong>APIS &amp; AUTH &gt; Credentials</strong>.</li>
137  <li>Under OAuth, click <strong>Create new Client ID</strong>.</li>
138  <li>In the <strong>Create Client ID</strong> dialog, select <strong>Web Application</strong> as
139the application type, and click <strong>Create Client ID</strong>.</li>
140  <li>Copy the value from <strong>Client ID for web application &gt; Client ID</strong>.
141This client ID represents a Google account "scope" that you will use to generate an {@code id_token}.</li>
142</ol>
143
144<p>Once you've followed the above steps and gotten a client ID from Google Developers Console,
145 you're ready to add this feature to your app. First check the device for the presence of a Google
146account. For example:</p>
147
148<pre>// This snippet takes the simple approach of using the first returned Google account,
149// but you can pick any Google account on the device.
150public String getAccount() {
151    Account[] accounts = AccountManager.get(getActivity()).
152        getAccountsByType(&quot;com.google&quot;);
153    if (accounts.length == 0) {
154        return null;
155    }
156    return accounts[0].name;
157}</pre>
158
159<p>Next, get an authentication token ({@code id_token}) by using the <code><a href=
160"http://developer.android.com/reference/com/google/android/gms/auth/GoogleAuthUtil.html">GoogleAuthUtil</a></code>
161class. For example:</p>
162
163<pre>String accountName = getAccount();
164
165// Initialize the scope using the client ID you got from the Console.
166final String scope = &quot;audience:server:client_id:&quot;
167        + &quot;1262xxx48712-9qs6n32447mcj9dirtnkyrejt82saa52.apps.googleusercontent.com&quot;;
168String id_token = null;
169try {
170    id_token = GoogleAuthUtil.getToken(context, accountName, scope);
171} catch (Exception e) {
172    log(&quot;exception while getting id_token: &quot; + e);
173}
174...</pre>
175
176<p>Now use <code>id_token</code> to authenticate your request.
177This add operation returns a {@code notification_key}.
178Third parties must save this {@code notification_key} (as well as its mapping to the
179<code>notification_key_name</code>)
180to use in subsequent operations. Note that a client request only takes a single regID.
181The only operations supported on the client side are add/remove.</p>
182
183<pre>request:
184{
185   &quot;operation&quot;: &quot;add&quot;,
186   &quot;notification_key_name&quot;: &quot;appUser-Chris&quot;,
187   &quot;registration_ids&quot;: [&quot;4&quot;]
188   &quot;id_token&quot;: &quot;id_token&quot;
189}</pre>
190
191<h3 id="request-client">Request format</h3>
192
193<p>To send a message in cases where your notification key is generated on the client,
194the application server issues a POST request to
195<code>https://android.googleapis.com/gcm/googlenotification</code>.</p>
196
197<p>Here is the HTTP request header you should use for all add/remove operations. The
198client side doesn't support the create operation;
199the add operation has the effect of creating the notification key if it doesn't already
200exist:</p>
201
202<pre>content-type: "application/json"
203Header : "project_id": &lt;projectID&gt;
204</pre>
205
206<p>Note that the authentication token is passed in the JSON body as shown above, not the header.
207This is different from the server case.</p>
208
209
210<h2 id="add">Add Registration IDs</h2>
211
212<p>This example shows how to add registration IDs for a given notification key.
213The maximum number of members allowed for a {@code notification_key} is 20.</p>
214
215<p>Note that the <code>notification_key_name</code> is not strictly required for
216adding/removing regIDs. But including it protects you against accidentally using
217the incorrect <code>notification_key</code>.</p>
218
219<pre>request:
220{
221   &quot;operation&quot;: &quot;add&quot;,
222   &quot;notification_key_name&quot;: &quot;appUser-Chris&quot;,
223   &quot;notification_key&quot;: &quot;aUniqueKey&quot;
224   &quot;registration_ids&quot;: [&quot;4&quot;, &quot;8&quot;, &quot;15&quot;, &quot;16&quot;, &quot;23&quot;, &quot;42&quot;]
225}</pre>
226
227<h2 id="remove">Remove Registration IDs</h2>
228
229<p>This example shows how to remove registration IDs for a given notification key:</p>
230<pre>request:
231{
232   &quot;operation&quot;: &quot;remove&quot;,
233   &quot;notification_key_name&quot;: &quot;appUser-Chris&quot;,
234   &quot;notification_key&quot;: &quot;aUniqueKey&quot;
235   &quot;registration_ids&quot;: [&quot;4&quot;, &quot;8&quot;, &quot;15&quot;, &quot;16&quot;, &quot;23&quot;, &quot;42&quot;]
236}</pre>
237
238<h2 id="upstream">Send Upstream Messages</h2>
239
240<p>To send an upstream (device-to-cloud) message, you must use the
241<a href="{@docRoot}reference/com/google/android/gms/gcm/GoogleCloudMessaging.html">
242{@code GoogleCloudMessaging}</a> API. Specifying a {@code notification_key} as the target
243for an upstream message allows a user on one device to send a message to other
244devices in the notification group&mdash;for example, to dismiss a notification.
245Here is an example that shows targeting a {@code notification_key}:</p>
246
247<pre>GoogleCloudMessaging gcm = GoogleCloudMessaging.get(context);
248String to = NOTIFICATION_KEY;
249AtomicInteger msgId = new AtomicInteger();
250String id = Integer.toString(msgId.incrementAndGet());
251Bundle data = new Bundle();
252data.putString("hello", "world");
253
254gcm.send(to, id, data);
255</pre>
256
257<p>This call generates the necessary XMPP stanza for sending the message. The
258Bundle data consists of a key-value pair.</p>
259
260<p>For a complete example, see <a href="client.html">Implementing GCM Client</a>.
261
262<h2 id="response">Response Formats</h2>
263
264<p>This section shows examples of the responses that can be returned for
265notification key operations.</p>
266
267<h3 id="response-create">Create/add/remove operations</h3>
268
269<p>When you make a request to create a {@code notification_key} or to add/remove its
270regIDs, a successful response always returns the <code>notification_key</code>.
271Use the returned {@code notification_key} for sending messages:</p>
272
273<pre>HTTP status: 200
274{
275    &quot;notification_key&quot;: &quot;aUniqueKey&quot;,   // to be used for sending
276}</pre>
277
278
279<h3 id="response-send">Send operations</h3>
280
281<p>For a send operation that has a {@code notification_key} as its target, the
282possible responses are success, partial success, and failure.</p>
283
284<p>Here is an example of "success"&mdash;the {@code notification_key} has 2 regIDs
285associated with it, and the message was successfully sent to both of them:</p>
286
287<pre>{
288  "success": 2,
289  "failure": 0
290}</pre>
291
292<p>Here is an example of "partial success"&mdash;the {@code notification_key} has
2933 regIDs associated with it. The message was successfully send to 1 of the regIDs,
294but not to the other 2. The response message lists the regIDs that failed to
295receive the message:</p>
296
297<pre>{
298  "success":1,
299  "failure":2,
300  "failed_registration_ids":[
301     "regId1",
302     "regId2"
303  ]
304}</pre>
305
306<p>In the case of failure, the response has HTTP code 503 and no JSON. When a message
307fails to be delivered to one or more of the regIDs associated with a {@code notification_key},
308the 3rd-party server should retry.</p>
309