• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1page.title=Getting Started with GCM
2page.tags="cloud","push","messaging"
3@jd:body
4
5<div id="qv-wrapper">
6<div id="qv">
7
8
9<h2>In this document</h2>
10
11<ol class="toc">
12<li><a href="#create-proj">Creating a Google API Project</a></li>
13<li><a href="#gcm-service">Enabling the GCM Service</a></li>
14<li><a href="#access-key">Obtaining an API Key</a></li>
15<li><a href="#android-app">Writing the Android Application</a>
16</ol>
17
18<h2>See Also</h2>
19
20<ol class="toc">
21<li><a href="https://code.google.com/apis/console">Google APIs Console page</a></li>
22<li><a href="{@docRoot}google/gcm/helper.html">Using the GCM Helper Libraries</a></li>
23<li><a href="https://services.google.com/fb/forms/gcm/" class="external-link" target="_android">CCS and User Notifications Signup Form</a></li>
24</ol>
25
26</div>
27</div>
28
29<p>The sections below guide you through the process of setting up a GCM
30implementation.
31Before you start, make sure to <a href="/google/play-services/setup.html">set up
32the Google Play Services SDK</a>. You need this SDK to use the <a href="{@docRoot}reference/com/google/android/gms/gcm/GoogleCloudMessaging.html">{@code GoogleCloudMessaging}</a> methods. Strictly speaking, the only thing you absolutely need this API for is upstream (device-to-cloud) messaging, but it also offers a streamlined registration API that is recommended.</p>
33
34
35<!--the basic steps are:
36
37<ul>
38<li>Creating a Google APIs Project</li>
39<li>Setting up GCM in your apps</li>
40<li>Integrating </li>
41
42<p>Note that a full GCM implementation requires a server-side implementation, in addition to the client implementation in your app. For complete information, make sure to read the <a href="/google/gcm/index.html">Google Cloud Messaging documentation</a>.
43-->
44
45
46
47
48<h2 id="create-proj">Creating a Google API project</h2>
49<p>To create a Google API project:</p>
50<ol>
51  <li>Open the <a href="https://code.google.com/apis/console">Google APIs Console page</a>.
52  </li>
53  <li>If you haven't created an API project yet, this page will prompt you to do so:
54  <p><img src="{@docRoot}images/gcm/gcm-create-api-proj.png" class="screenshot" /></p>
55<p class="note"><strong>Note:</strong> If you already have existing projects, the first page you see will be the <strong>Dashboard</strong> page. From there you can create a new project by opening the project drop-down menu (upper left corner) and choosing <strong>Other projects > Create</strong>.</p></li>
56  <li> Click <strong>Create project</strong>.
57    Your browser URL will change to something like:</li>
58
59<pre> https://code.google.com/apis/console/#project:<strong>4815162342</strong></pre>
60
61  <li> Take note of the value after <code>#project:</code> (4815162342 in this example). This is your project number, and it will be used later on as the GCM sender ID.</li>
62
63</ol>
64<h2 id="gcm-service">Enabling the GCM Service</h2>
65<p>To enable the GCM service:</p>
66<ol>
67  <li> In the main Google APIs Console page, select <strong>Services</strong>.</li>
68  <li>Turn the <strong>Google Cloud Messaging</strong> toggle to ON.</li>
69  <li>In the Terms of Service page, accept the terms.
70  </li>
71</ol>
72<h2 id="access-key">Obtaining an API Key</h2>
73<p>To obtain an API  key:</p>
74<ol>
75  <li> In the main Google APIs Console page, select <strong>API Access</strong>. You will see a screen that resembles the following:</li><br />
76
77
78<img src="{@docRoot}images/gcm/gcm-api-access.png" style="width:400px;padding:4px;margin-bottom:0em;">
79
80
81  <li>Click  <strong>Create new Server key</strong>. Either a server key or a browser key should work. The advantage to using a server key is that it allows you to whitelist IP addresses. The following screen appears:</li><br />
82
83
84<img src="{@docRoot}images/gcm/gcm-config-server-key.png" style="width:400px;padding:4px;margin-bottom:0em;">
85
86
87  <li>Click <strong>Create</strong>:</li><br />
88
89
90<img src="{@docRoot}images/gcm/gcm-api-key.png" style="width:400px;padding:4px;margin-bottom:0em;">
91
92
93
94</ol>
95<p> Take note of the <strong>API key</strong> value (<code>YourKeyWillBeShownHere</code>) in this example, as it will be used later on.</p>
96<p class="note"><strong>Note:</strong> If you need to rotate the key, click  <strong>Generate new key</strong>. A new key  will be created while the old one will still be active for up to 24 hours. If you want to get rid of the old key immediately (for example, if you feel it was compromised), click <strong>Delete key</strong>.</p>
97
98
99<h2 id="android-app">Writing the Android Application</h2>
100<p>This section describes the steps involved in writing an Android application that uses GCM.</p>
101
102<h4 id="manifest">Step 1: Make the following changes in the application's Android manifest</h4>
103<ul>
104  <li>The <code>com.google.android.c2dm.permission.RECEIVE</code> permission so the Android application can register and receive messages.</li>
105  <li>The <code>android.permission.INTERNET</code> permission so the Android application can send the registration ID to the 3rd party server.</li>
106  <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>
107  <li>The <code>android.permission.WAKE_LOCK</code> permission so the application can keep the processor from sleeping when a message is received. Optional&mdash;use only if the app wants to keep the device from sleeping.</li>
108  <li>An <code>applicationPackage + &quot;.permission.C2D_MESSAGE</code> permission to prevent other Android applications from registering and receiving the Android application's
109messages. The permission name must exactly match this pattern&mdash;otherwise the Android application will not receive the messages.</li>
110   <li>A receiver for <code>com.google.android.c2dm.intent.RECEIVE</code>, with the category set
111as <code>applicationPackage</code>. The receiver should require the <code>com.google.android.c2dm.SEND</code> permission, so that only the GCM
112Framework can send a message to it. Note that the receiving
113of messages is implemented as an <a href="{@docRoot}guide/components/intents-filters.html">intent</a>.</li>
114  <li>An intent service to handle the intents received by the broadcast receiver. Optional.</li>
115  <li>If the GCM feature is critical to the Android application's function, be sure to
116set <code>android:minSdkVersion=&quot;8&quot;</code> in the manifest. This
117ensures that the Android application cannot be installed in an environment in which it
118could not run properly. </li>
119</ul>
120
121<p>Here are excerpts from a manifest that supports GCM:</p>
122
123<pre class="prettyprint pretty-xml">
124&lt;manifest package="com.example.gcm" ...&gt;
125
126    &lt;uses-sdk android:minSdkVersion="8" android:targetSdkVersion="17"/&gt;
127    &lt;uses-permission android:name="android.permission.INTERNET" /&gt;
128    &lt;uses-permission android:name="android.permission.GET_ACCOUNTS" /&gt;
129    &lt;uses-permission android:name="android.permission.WAKE_LOCK" /&gt;
130    &lt;uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" /&gt;
131
132    &lt;permission android:name="com.example.gcm.permission.C2D_MESSAGE"
133        android:protectionLevel="signature" /&gt;
134    &lt;uses-permission android:name="com.example.gcm.permission.C2D_MESSAGE" /&gt;
135
136    &lt;application ...&gt;
137        &lt;receiver
138            android:name=".MyBroadcastReceiver"
139            android:permission="com.google.android.c2dm.permission.SEND" &gt;
140            &lt;intent-filter&gt;
141                &lt;action android:name="com.google.android.c2dm.intent.RECEIVE" /&gt;
142                &lt;category android:name="com.example.gcm" /&gt;
143            &lt;/intent-filter&gt;
144        &lt;/receiver&gt;
145        &lt;service android:name=".MyIntentService" /&gt;
146    &lt;/application&gt;
147
148&lt;/manifest&gt;
149</pre>
150
151
152<h4>Step 2: Register for GCM</h4>
153
154<p>An Android application running on a mobile device registers to receive messages by calling
155the <a href="{@docRoot}reference/com/google/android/gms/gcm/GoogleCloudMessaging.html">{@code GoogleCloudMessaging}</a> method
156<a href="{@docRoot}reference/com/google/android/gms/gcm/GoogleCloudMessaging.html#register">{@code register(senderID...)}</a>.
157This method registers the application for GCM and returns the registration ID. This streamlined approach replaces the previous
158GCM registration process.</p>
159
160<h4> Step 3: Write your application</h4>
161
162<p>Finally, write your application. GCM offers a variety of ways to get the job done:</p>
163
164<ul>
165  <li>For your messaging server, you can either use the new <a href="ccs.html">GCM Cloud Connection Server</a> (CCS), the older <a href="gcm.html">GCM HTTP server</a>, or both in tandem.</li>
166  <li>To write your client application, you can use any of the following:
167    <ul>
168      <li>The helper libraries, which are described in the <a href="{@docRoot}google/gcm/demo.html">Demo App Tutorial</a> and <a href="{@docRoot}google/gcm/helper.html">Using the GCM Helper Libraries</a>.</li>
169      <li>The approach described in the <a href="{@docRoot}google/gcm/gcm.html#writing_apps">GCM Architectural Overview</a>.</li>
170      <li>Regardless, you must use the <a href="{@docRoot}reference/com/google/android/gms/gcm/GoogleCloudMessaging.html">{@code GoogleCloudMessaging}</a> APIs if you are doing upstream (device-to-cloud) messaging. Even if you are not doing upstream messaging, we recommend that you use this API to take advantage of the streamlined registration process&mdash;described above and shown in the following sample.</li>
171</ul>
172</li>
173
174</ul>
175
176<h5 id="gs_example">Example</h5>
177
178<p>Here is a sample application that illustrates how to use the <a href="{@docRoot}reference/com/google/android/gms/gcm/GoogleCloudMessaging.html">{@code GoogleCloudMessaging}</a> APIs. In this example, the sender is a <a href="{@docRoot}google/gcm/ccs.html">CCS</a> echo server. The sample consists of a main Activity ({@code DemoActivity}) and a broadcast receiver ({@code GcmBroadcastReceiver}).</p>
179
180<p>An Android application needs to register with GCM servers before it can receive messages. So in its {@code onCreate()} method, {@code DemoActivity} checks to see whether the app is registered with GCM and with the server:</p>
181
182<pre>public class DemoActivity extends Activity {
183
184    public static final String EXTRA_MESSAGE = "message";
185    public static final String PROPERTY_REG_ID = "registration_id";
186    /**
187     * You can use your own project ID instead. This sender is a test CCS
188     * echo server.
189     */
190    String GCM_SENDER_ID = "Your-Sender-ID";
191
192    // Tag for log messages.
193    static final String TAG = "GCMDemo";
194
195    TextView mDisplay;
196    GoogleCloudMessaging gcm;
197    AtomicInteger msgId = new AtomicInteger();
198    SharedPreferences prefs;
199    String regid;
200
201    &#64;Override
202    public void onCreate(Bundle savedInstanceState) {
203        super.onCreate(savedInstanceState);
204
205        // Make sure the app is registered with GCM and with the server
206        prefs = getSharedPreferences(DemoActivity.class.getSimpleName(),
207                Context.MODE_PRIVATE);
208        setContentView(R.layout.main);
209
210        mDisplay = (TextView) findViewById(R.id.display);
211
212        regid = prefs.getString(PROPERTY_REG_ID, null);
213
214        // If there is no registration ID, the app isn't registered.
215        // Call registerBackground() to register it.
216        if (regid == null) {
217            registerBackground();
218        }
219
220        gcm = GoogleCloudMessaging.getInstance(this);
221    }</pre>
222
223<p>If the app isn't registered, {@code DemoActivity} calls the following {@code registerBackground()} method to register it. Note that because GCM methods are blocking, this has to take place on a background thread. This sample uses {@link android.os.AsyncTask} to accomplish this:</p>
224
225<pre>private void registerBackground() {
226    new AsyncTask<Void, Void, String>() {
227        &#64;Override
228        protected String doInBackground(Void... params) {
229            String msg = "";
230            try {
231                regid = gcm.register(GCM_SENDER_ID);
232                msg = "Device registered, registration id=" + regid;
233
234                // You should send the registration ID to your server over HTTP,
235                // so it can use GCM/HTTP or CCS to send messages to your app.
236
237                // For this demo: we don't need to send it because the device
238                // will send upstream messages to a server that will echo back
239                // the message using the 'from' address in the message.
240
241                // Save the regid for future use - no need to register again.
242                SharedPreferences.Editor editor = prefs.edit();
243                editor.putString(PROPERTY_REG_ID, regid);
244                editor.commit();
245            } catch (IOException ex) {
246                msg = "Error :" + ex.getMessage();
247            }
248            return msg;
249        }
250        // Once registration is done, display the registration status
251        // string in the Activity's UI.
252        &#64;Override
253        protected void onPostExecute(String msg) {
254            mDisplay.append(msg + "\n");
255        }
256    }.execute(null, null, null);
257}</pre>
258
259<p>When the user clicks the app's <strong>Echo</strong> button, the app generates the necessary XMPP stanza for the message, which it sends to the echo server:</p>
260<pre>public void onClick(final View view) {
261    if (view == findViewById(R.id.send)) {
262        new AsyncTask<Void, Void, String>() {
263            &#64;Override
264            protected String doInBackground(Void... params) {
265                String msg = "";
266                try {
267                    Bundle data = new Bundle();
268                    // data is a key-value pair.
269                    data.putString("hello", "world");
270                    String id = Integer.toString(msgId.incrementAndGet());
271                    gcm.send(GCM_SENDER_ID + "&#64;gcm.googleapis.com", id, data);
272                    msg = "Sending message";
273                } catch (IOException ex) {
274                    msg = "Error :" + ex.getMessage();
275                }
276                return msg;
277            }
278
279            &#64;Override
280            protected void onPostExecute(String msg) {
281                // Displays the text "Sending message"
282                mDisplay.append(msg + "\n");
283            }
284        }.execute(null, null, null);
285    }
286}</pre>
287
288<p>As described above in <a href="#manifest">Step 1</a>, the app includes a broadcast receiver for the <code>com.google.android.c2dm.intent.RECEIVE</code> intent. This 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 handling the GCM message. In this sample the receiver's {@code onReceive()} method calls {@code sendNotification()} to put the message into a notification:</p>
289
290<pre>public class GcmBroadcastReceiver extends BroadcastReceiver {
291    static final String TAG = "GCMDemo";
292    public static final int NOTIFICATION_ID = 1;
293    private NotificationManager mNotificationManager;
294    NotificationCompat.Builder builder;
295    Context ctx;
296
297
298    &#64;Override
299    public void onReceive(Context context, Intent intent) {
300        GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(context);
301        ctx = context;
302        String messageType = gcm.getMessageType(intent);
303        if (GoogleCloudMessaging.MESSAGE_TYPE_SEND_ERROR.equals(messageType)) {
304            sendNotification("Send error: " + intent.getExtras().toString());
305        } else if (GoogleCloudMessaging.MESSAGE_TYPE_DELETED.equals(messageType)) {
306            sendNotification("Deleted messages on server: " +
307                    intent.getExtras().toString());
308        } else {
309            sendNotification("Received: " + intent.getExtras().toString());
310        }
311        setResultCode(Activity.RESULT_OK);
312    }
313
314    // Put the GCM message into a notification and post it.
315    private void sendNotification(String msg) {
316      mNotificationManager = (NotificationManager)
317              ctx.getSystemService(Context.NOTIFICATION_SERVICE);
318
319      PendingIntent contentIntent = PendingIntent.getActivity(ctx, 0,
320          new Intent(ctx, DemoActivity.class), 0);
321
322      NotificationCompat.Builder mBuilder =
323          new NotificationCompat.Builder(ctx)
324          .setSmallIcon(R.drawable.ic_stat_notification)
325          .setContentTitle("GCM Notification")
326          .setStyle(new NotificationCompat.BigTextStyle()
327                     .bigText(msg))
328          .setContentText(msg);
329
330     mBuilder.setContentIntent(contentIntent);
331     mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
332    }
333}</pre>
334