public class

GoogleCloudMessaging

extends Object
java.lang.Object
   ↳ com.google.android.gms.gcm.GoogleCloudMessaging

Class Overview

The class you use to write a GCM-enabled client application that runs on an Android device. Client applications can receive GCM messages and optionally send messages of their own back to the server.

This class requires Google Play services version 3.1 or higher. For a detailed discussion of how to write a GCM client app, see Implementing GCM Client.

To send or receive messages, your application first needs to get a registration ID. The registration ID identifies the device and application, and also determines which 3rd-party application servers are allowed to send messages to this application instance.

To get a registration ID, you must supply one or more sender IDs. A sender ID is a project number you acquire from the API console, as described in Getting Started. The sender ID is used in the registration process to identify a 3rd-party application server that is permitted to send messages to the device. The following snippet shows you how to call the register() method. For a more comprehensive example, see Implementing GCM Client.

 String SENDER_ID = "My-Sender-ID";
 GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(context);
 String registrationId = gcm.register(SENDER_ID);
 // Upload the registration ID to your own server
 // The request to your server should be authenticated if your app is using accounts.
 

In order to receive GCM messages, you need to declare a permission and a BroadcastReceiver in your manifest. This is a backward-compatible subset of what was required in previous versions of GCM.

To allow the application to use GCM, add this permission to the manifest:

<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />

GCM delivers messages as a broadcast. The receivers must be registered in the manifest in order to wake up the application.

The com.google.android.c2dm.permission.SEND permission is held by Google Play services. This prevents other code from invoking the broadcast receiver. Here is an excerpt from a sample manifest:

 <receiver android:name=".MyReceiver" android:exported="true"
     android:permission="com.google.android.c2dm.permission.SEND" >
     <intent-filter>
        <action android:name="com.google.android.c2dm.intent.RECEIVE" />
        <category android:name="YOUR_PACKAGE_NAME" />
     </intent-filter>
 </receiver>

When a GCM connection server delivers the message to your client app, the BroadcastReceiver receives the message as an intent. You can either process the intent in the BroadcastReceiver, or you can pass off the work of processing the intent to a service (typically, an IntentService). If you use a service, your broadcast receiver should be an instance of WakefulBroadcastReceiver, to hold a wake lock while the service is doing its work.

When processing the intent GCM passes into your app's broadcase receiver, you can determine the message type by calling getMessageType(intent). For example:

 GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
 String messageType = gcm.getMessageType(intent);
 ...
 // Filter messages based on message type. It is likely that GCM will be extended in the future
 // with new message types, so just ignore message types you're not interested in, or that you
 // don't recognize.
 if (GoogleCloudMessaging.MESSAGE_TYPE_SEND_ERROR.equals(messageType)) {
    // It's an error.
 } else if (GoogleCloudMessaging.MESSAGE_TYPE_DELETED.equals(messageType)) {
    // Deleted messages on the server.
 } else if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE.equals(messageType)) {
    // It's a regular GCM message, do some work.
 }
 

If you are using the XMPP-based Cloud Connection Server, your client app can send upstream messages back to the server. For example:

 gcm.send(SENDER_ID + "@gcm.googleapis.com", id, data);
 
For a more details, see Implementing GCM Client.

Summary

Constants
String ERROR_MAIN_THREAD The GCM register() and unregister() methods are blocking.
String ERROR_SERVICE_NOT_AVAILABLE The device can't read the response, or there was a 500/503 from the server that can be retried later.
String MESSAGE_TYPE_DELETED Returned by getMessageType(Intent) to indicate that the server deleted some pending messages because they were collapsible.
String MESSAGE_TYPE_MESSAGE Returned by getMessageType(Intent) to indicate a regular message.
String MESSAGE_TYPE_SEND_ERROR Returned by getMessageType(Intent) to indicate a send error.
Public Constructors
GoogleCloudMessaging()
Public Methods
void close()
Must be called when your application is done using GCM, to release internal resources.
synchronized static GoogleCloudMessaging getInstance(Context context)
Return the singleton instance of GCM.
String getMessageType(Intent intent)
Return the message type from an intent passed into a client app's broadcast receiver.
String register(String... senderIds)
Register the application for GCM and return the registration ID.
void send(String to, String msgId, long timeToLive, Bundle data)
Send an upstream ("device to cloud") message.
void send(String to, String msgId, Bundle data)
Send an upstream ("device to cloud") message.
void unregister()
Unregister the application.
[Expand]
Inherited Methods
From class java.lang.Object

Constants

public static final String ERROR_MAIN_THREAD

The GCM register() and unregister() methods are blocking. You should not run them in the main thread or in broadcast receivers.

Constant Value: "MAIN_THREAD"

public static final String ERROR_SERVICE_NOT_AVAILABLE

The device can't read the response, or there was a 500/503 from the server that can be retried later. The application should use exponential back off and retry.

Constant Value: "SERVICE_NOT_AVAILABLE"

public static final String MESSAGE_TYPE_DELETED

Returned by getMessageType(Intent) to indicate that the server deleted some pending messages because they were collapsible.

Constant Value: "deleted_messages"

public static final String MESSAGE_TYPE_MESSAGE

Returned by getMessageType(Intent) to indicate a regular message.

Constant Value: "gcm"

public static final String MESSAGE_TYPE_SEND_ERROR

Returned by getMessageType(Intent) to indicate a send error. The intent includes the message ID of the message and an error code.

Constant Value: "send_error"

Public Constructors

public GoogleCloudMessaging ()

Public Methods

public void close ()

Must be called when your application is done using GCM, to release internal resources.

public static synchronized GoogleCloudMessaging getInstance (Context context)

Return the singleton instance of GCM.

public String getMessageType (Intent intent)

Return the message type from an intent passed into a client app's broadcast receiver. There are two general categories of messages passed from the server: regular GCM messages, and special GCM status messages. The possible types are:

You can use this method to filter based on message type. Since it is likely that GCM will be extended in the future with new message types, just ignore any message types you're not interested in, or that you don't recognize.

Returns
  • The message type or null if the intent is not a GCM intent

public String register (String... senderIds)

Register the application for GCM and return the registration ID. You must call this once, when your application is installed, and send the returned registration ID to the server.

Repeated calls to this method will return the original registration ID.

If you want to modify the list of senders, you must call unregister() first.

Most applications use a single sender ID. You may use multiple senders if different servers may send messages to the app or for testing.

Parameters
senderIds list of project numbers or Google accounts identifying who is allowed to send messages to this application.
Returns
  • registration id
Throws
IOException

public void send (String to, String msgId, long timeToLive, Bundle data)

Send an upstream ("device to cloud") message. You can only use the upstream feature if your GCM implementation uses the XMPP-based Cloud Connection Server. The current limits for max storage time and number of outstanding messages per application are documented in the GCM Developers Guide.

Parameters
to string identifying the receiver of the message. For GCM projects IDs the value is [email protected]. The SENDER_ID should be one of the sender IDs used in register().
msgId ID of the message. This is generated by the application. It must be unique for each message. This allows error callbacks and debugging.
timeToLive If 0, we'll attempt to send immediately and return an error if we're not connected. Otherwise, the message will be queued. As for server-side messages, we don't return an error if the message has been dropped because of TTL—this can happen on the server side, and it would require extra communication.
data key/value pairs to be sent. Values must be String, any other type will be ignored.
Throws
IllegalArgumentException
IOException

public void send (String to, String msgId, Bundle data)

Send an upstream ("device to cloud") message. You can only use the upstream feature if your GCM implementation uses the XMPP-based Cloud Connection Server. The message will be queued if we don't have an active connection for the max interval.

Parameters
to string identifying the receiver of the message. For GCM project IDs the value is [email protected]. The SENDER_ID should be one of the sender IDs used in register().
msgId ID of the message. This is generated by the application. It must be unique for each message. This allows error callbacks and debugging.
data key/value pairs to be sent. Values must be String—any other type will be ignored.
Throws
IllegalArgumentException
IOException

public void unregister ()

Unregister the application. Calling unregister() stops any messages from the server. This is a blocking call—you shouldn't call it from the UI thread. You should rarely (if ever) need to call this method. Not only is it expensive in terms of resources, but it invalidates your registration ID, which you should never change unnecessarily. A better approach is to simply have your server stop sending messages. Only use unregister if you want to change your sender ID.

Throws
IOException if we can't connect to server to unregister.