This guide provides instructions, examples, and information about options for sending simple downstream messages with GCM. In this context, "simple" means messages sent from the app server to a client app on a device, as opposed to routing messages through topics or device groups.
Sending downstream messages from the server
To address or "target" a downstream message, the app
server sets to with the receiving client app's registration token.
You can send notification messages with predefined fields, or custom data messages; see
Notifications and data in the message payload for details on payload support. Examples in
this page show how to send data messages to a topic in HTTP and XMPP protocols.
HTTP POST Request
https://gcm-http.googleapis.com/gcm/send
Content-Type:application/json
Authorization:key=AIzaSyZ-1u...0GBYzPu7Udno5aA
{ "data": {
"score": "5x1",
"time": "15:10"
},
"to" : "bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1..."
}
XMPP Message
<message id="">
<gcm xmlns="google:mobile:data">
{ "data": {
"score": "5x1",
"time": "15:10"
},
"to" : "bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1..."
}
</gcm>
</message>
For the full list of message options available when sending downstream messages to client app, see the reference information for your chosen connection server protocol, HTTP or XMPP.
Receiving messages on an Android client app
To receive downstream messages, each client app needs to obtain a registration token and extend some specific Android services as described in this section. For full detail on implementing an Android client app, see Set up a GCM Client App on Android.
Receive and handle messages
To receive simple downstream messages, use a service that extendsGcmListenerService to handle
messages captured by GcmReceiver. GcmReceiver extends WakefulBroadcastReceiver,
guaranteeing that the CPU is awake so that your listener service can complete its task.
By overriding the method GcmListenerService.onMessageReceived,
you can perform actions based on the received message:
@Override
public void onMessageReceived(String from, Bundle data) {
String message = data.getString("message");
Log.d(TAG, "From: " + from);
Log.d(TAG, "Message: " + message);
if (from.startsWith("/topics/")) {
// message received from some topic.
} else {
// normal downstream message.
}
// ...
}
Receive and handle messages with notification in the payload
When your app is in the background, Android
directs messages with notification to the system tray.
A user click on a notification opens
the app launcher by default.
If you want to open your app and perform
a specific action, set click_action in the
notification payload and map
it to an intent filter in the Activity you want to launch. For example, set
click_action to OPEN_ACTIVITY_1 to trigger an
intent filter like the following:
<intent-filter> <action android:name="OPEN_ACTIVITY_1" /> <category android:name="android.intent.category.DEFAULT" /> </intent-filter>
Receiving messages on an iOS client app
To receive downstream messages, each client app needs to obtain a registration token and implement some methods on the GCMService and AppDelegate APIs.
Receive and handle messages
Implement AppDelegate application:didReceiveRemoteNotification: to handle
messages received when the client app is in in the foreground or when the message
is
collapsible.
The message is a dictionary of keys and values.
For more information on implementing GCM's downstream message routing options, see Device Group Messaging and Topic Messaging.
When the client app receives a message,
call
[GCMService appDidReceiveMessage:<userInfo>]
to acknowledge receipt of that message to the GCM connection server:
- (void)application:(UIApplication *)application
didReceiveRemoteNotification:(NSDictionary *)userInfo {
NSLog(@"Notification received: %@", userInfo);
// This works only if the app started the GCM service
[[GCMService sharedInstance] appDidReceiveMessage:userInfo];
// Handle the received message
// ...
}
- (void)application:(UIApplication *)application
didReceiveRemoteNotification:(NSDictionary *)userInfo
fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))handler {
NSLog(@"Notification received: %@", userInfo);
// This works only if the app started the GCM service
[[GCMService sharedInstance] appDidReceiveMessage:userInfo];
// Handle the received message
// Invoke the completion handler passing the appropriate UIBackgroundFetchResult value
// ...
}
Receive and handle messages with notification in the payload
When your app is in the background, iOS
directs messages with notification to the system tray.
A user click on a notification
opens the app, and the content of the notification is passed to a
didReceiveRemoteNotification callback if implemented in the
AppDelegate.
If you want to open your app and perform
a specific action, set click_action in the
notification payload. Use the value that you would use for the
category key in the APNs payload.
Stop receiving messages
To stop receiving all messages, use the asynchronous method
deleteTokenWithAuthorizedEntity:authorizedEntity:scope:handler
to invalidate the client app’s GCM registration token. Call this method with the
app server sender ID and the kGGLInstanceIDScopeGCM scope:
[[GGLInstanceID sharedInstance] deleteTokenWithAuthorizedEntity:@"your-sender-id" scope: kGGLInstanceIDScopeGCM handler:deletedAppToken];
The NSError object is nil if the command is successful. NSError contains the
failure reason if the command fails. For more
information, see Common error codes.
Stop receiving data messages
To stop receiving messages with data payload sent via GCM, call disconnect on the application's main thread:
- (void)applicationDidEnterBackground:(UIApplication *)application {
[[GCMService sharedInstance] disconnect];
// ...
}
After it is disconnected, the client app stops receiving messages, except those
with notification payload, from the GCM connection server.
It continues to receive messages with notification payload
until
deletetokenWithAuthorizedEntity is called.
Call disconnect when the client app is in the background or when it needs to stop
exponential background connection retry.