100% found this document useful (1 vote)
590 views22 pages

Google Cloud Messaging Report

This document is a self-study report submitted by Vineet Garg on Google Cloud Messaging (GCM). It includes a certificate signed by the assistant professor Indu Singh to verify the work is Vineet's own. The report provides an overview of GCM including its key concepts such as components, credentials, and architectural overview describing how GCM connects a client app, 3rd party app server, and GCM connection servers. It also describes the lifecycle flow of enabling GCM on a client app, sending messages from an app server, and receiving messages on the client app.

Uploaded by

Vineet Garg
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
590 views22 pages

Google Cloud Messaging Report

This document is a self-study report submitted by Vineet Garg on Google Cloud Messaging (GCM). It includes a certificate signed by the assistant professor Indu Singh to verify the work is Vineet's own. The report provides an overview of GCM including its key concepts such as components, credentials, and architectural overview describing how GCM connects a client app, 3rd party app server, and GCM connection servers. It also describes the lifecycle flow of enabling GCM on a client app, sending messages from an app server, and receiving messages on the client app.

Uploaded by

Vineet Garg
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 22

SELF STUDY REPORT

ON

Google Cloud Messaging

Department of Computer Engineering (COE)

Submitted By:

VINEET GARG
2K13/CO/142

CERTIFICATE
This is to certify that this project report entitled Google Cloud Messaging
submitted by Vineet Garg (2K13/CO/142) in partial fulfilment for the requirements
for the award of Bachelor of Technology Degree in Computer Engineering (COE) at
Delhi Technological University is an authentic work carried out by the student under
my supervision and guidance.
To the best of my knowledge, the matter embodied in the thesis has not been
submitted to any other university or institute for the award of any degree or diploma.

Ms. INDU SINGH


(Asst. Professor)
Dept. of Computer Engineering
Delhi Technological University

ACKNOWLEDGEMENT
I would like to express my greatest gratitude to the people who have helped and
supported me throughout the project.
Firstly, I express my heartiest gratitude towards the authorities who gave me a chance
to explore the intricacies of various aspects of Google Cloud Messaging. I would
also sincerely thank my esteemed mentor, Ms. Indu Singh, who lent a huge helping
hand in the process of making this project with her valuable guidance and blessings.
I would also not forget to thank the department authorities, who played an
indispensable role in the process. In the end, I would thank my friends and family for
their extended support throughout the project.

Vineet Garg

ABSTRACT
Google Cloud Messaging for Android (GCM) is a service that helps developers to
send data from servers to their Android applications on Android devices. The service
was unveiled on June 27, 2012, at Google I/O 2012 held at the Moscone Center in
San Francisco . The GCM service handles all aspects of queuing of messages and
delivery to the target Android application running on the target device. It is
completely free whatever your messaging needs are and it can be used in some
applications like smart notification systems.

This report gives an overview about the Google GCM service and about its working
and usage.

INDEX
S.No

Topic

Page no.

Introduction

Key Concepts

Architectural Overview

Lifecycle Flow

10

Implementing Gcm Service

12

Properties of Payload

18

Possible Problems

19

Applications

20

Conclusion

21

10

References

22

INTRODUCTION
Google Cloud Messaging (GCM) is a service that enables developers to send data
from servers to both Android applications or Chrome apps and extensions.
The service provides a simple, lightweight mechanism that servers can use to tell
mobile applications to contact the server directly, to fetch updated application or user
data. The service handles all aspects of queueing of messages and delivery to the
target application running on the target device.
The free service has the ability to send a lightweight message informing the Android
application of new data to be fetched from the server. Larger messages can be sent
with up to 4 KB of payload data. Each notification message size is limited to 1024
bytes, and Google limits the number of messages a sender sends in aggregate, and the
number of messages a sender sends to a specific device.
Applications on an Android device dont need to be running to receive messages. The
system will wake up the application via a mechanism called Intent Broadcast when
the message arrives, as long as the application is set up with the proper broadcast
receiver and permissions. GCM does not provide any built-in user interface or other
handling for message data. Instead, it simply passes raw message data received
straight to the application, which has full control of how to handle it. For example,
the application might post a notification, display a custom user interface, or silently
sync data.

KEY CONCEPTS
This table summarizes the key terms and concepts involved in GCM. It is divided
into these categories:
Components The entities that play a primary role in GCM.
Credentials The IDs and tokens that are used in different stages of GCM to ensure that
all parties have been authenticated, and that the message is going to the correct place.
Table 1. GCM components and credentials.
Components

Client App

The GCM-enabled Android application that is running on a device. This must


be a 2.2 Android device that has Google Play Store installed, and it must 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.

3rd-party
Application
Server

An application server that you write as part of implementing GCM. The 3rdparty application server sends data to an Android application on the device via
the GCM connection server.

GCM
Connection
Servers

The Google-provided servers involved in taking messages from the 3rd-party


application server and sending them to the device.
Credentials

Sender ID

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.

Application ID

The Android application that is registering to receive messages. The Android


application is identified by the package name from the manifest. This ensures
that the messages are targeted to the correct Android application.

An ID issued by the GCM servers to the Android application that allows it to


receive messages. Once the Android application has the registration ID, it sends
it to the 3rd-party application server, which uses it to identify each device that
has registered to receive messages for a given Android application. In other
words, a registration ID is tied to a particular Android application running on a
Registration ID particular device. Note that registration IDs must be kept secret.
Note: If you use backup and restore, you should explicitly avoid backing up
registration IDs. When you back up a device, apps back up shared prefs
indiscriminately. If you don't explicitly exclude the GCM registration ID, it
could get reused on a new device, which would cause delivery errors.
Google User
Account

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.

Sender Auth

An API key that is saved on the 3rd-party application server that gives the

Token

application server authorized access to Google services. The API key is


included in the header of POST requests that send messages.

ARCHITECTURAL OVERVIEW
A GCM implementation includes a Google-provided connection server, a 3rd-party
app server that interacts with the connection server, and a GCM-enabled client app
running on an Android device:

Illustration 1: GCM Architecture

This is how these components interact:


Google-provided GCM Connection Servers take messages from a 3rd-party

application server and send these messages to a GCM-enabled Android


application (the "client app") running on a device. Currently Google provides
connection servers for HTTP and XMPP.
The 3rd-Party Application Server is a component that you implement to
work with your chosen GCM connection server(s). App servers send messages
to a GCM connection server; the connection server enqueues and stores the
message, and then sends it to the device when the device is online. For more
information, see Implementing GCM Server.
The Client App is a GCM-enabled Android application running on a device.
To receive GCM messages, this app must register with GCM and get a
registration ID. If you are using the XMPP (CCS) connection server, the client
app can send "upstream" messages back to the connection server. For more
information on how to implement the client app, see Implementing GCM
Client.

LIFECYCLE FLOW
(a)Enable GCM. An Android application running on a mobile device registers to
receive messages.
(b)Send a message. A 3rd-party application server sends messages to the device.
(c)Receive a message. An Android application receives a message from a GCM
server.

These processes are described in more detail below.


(a) Enable GCM
The first time the Android application needs to use the messaging service, it calls
the GoogleCloudMessaging method register(), as discussed in Implementing
GCM Client. The register() method returns a registration ID. The Android
application should store this ID for later use (for instance, to check in onCreate()
if it is already registered).
(b) Send a message
Here is the sequence of events that occurs when the application server sends a
message:
1. The application server sends a message to GCM servers.
2. Google enqueues and stores the message in case the device is offline.
3. When the device is online, Google sends the message to the device.
4. On the device, the system broadcasts the message to the specified Android
application via Intent broadcast with proper permissions, so that only the
targeted Android application gets the message. This wakes the Android
application up. The Android application does not need to be running
beforehand to receive the message.
5. The Android application processes the message. If the Android application
is doing non-trivial processing, you may want to grab a
PowerManager.WakeLock and do any processing in a service.
An Android application can unregister GCM if it no longer wants to receive
messages.
10

(c) Receive a message


This is the sequence of events that occurs when an Android application installed
on a mobile device receives a message:
1. The system receives the incoming message and extracts the raw key/value
pairs from the message payload, if any.
2. The system passes the key/value pairs to the targeted Android application in
a com.google.android.c2dm.intent.RECEIVE Intent as a set of
extras.
3. The Android application extracts the raw data from the
com.google.android.c2dm.intent.RECEIVE Intent by key and
processes the data.

11

IMPLEMENTING GCM SERVICE


1)

Create project on Google Developer Console and get project

number.
2)

Enable GCM service on that project from API's and Auth section.

3)

Create new Server Key from APIs & auth > Credentials.

4)

Implement GCM client

a) Set up Setup Google Play Services SDK for the Android project.

b) Edit applications manifest file and set up required permissions and


package and necessary broadcast reciever.

12

c) Write your application:


i) Write check play service for checking is the device
compatible with GCM or not.
private boolean checkPlayServices() {
int resultCode =
GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if (resultCode != ConnectionResult.SUCCESS) {
if
(GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
GooglePlayServicesUtil.getErrorDialog(resultCode,
this,
PLAY_SERVICES_RESOLUTION_REQUEST).show();
} else {
Log.i(TAG, "This device is not supported.");
finish();
}
return false;
}
return true;
}

ii) Register device to GCM server.


private String getRegistrationId(Context context) {
final SharedPreferences prefs = getGCMPreferences(context);
String registrationId = prefs.getString(PROPERTY_REG_ID, "");
if (registrationId.isEmpty()) {
Log.i(TAG, "Registration not found.");
return "";
}
// Check if app was updated; if so, it must clear the
registration ID
// since the existing regID is not guaranteed to work with the
new
// app version.
int registeredVersion = prefs.getInt(PROPERTY_APP_VERSION,
Integer.MIN_VALUE);
int currentVersion = getAppVersion(context);
if (registeredVersion != currentVersion) {
Log.i(TAG, "App version changed.");
return "";
}
return registrationId;
}

iii) Register Device Id on your own server.


13

private void registerInBackground() {


new AsyncTask() {
@Override
protected String doInBackground(Void... params) {
String msg = "";
try {
if (gcm == null) {
gcm =
GoogleCloudMessaging.getInstance(context);
}
regid = gcm.register(SENDER_ID);
msg = "Device registered, registration ID=" +
regid;
// You should send the registration ID to your
server over HTTP,
// so it can use GCM/HTTP or CCS to send messages
to your app.
// The request to your server should be
authenticated if your app
// is using accounts.
sendRegistrationIdToBackend();
// For this demo: we don't need to send it because
the device
// will send upstream messages to a server that
echo back the
// message using the 'from' address in the
message.
// Persist the regID - no need to register again.
storeRegistrationId(context, regid);
} catch (IOException ex) {
msg = "Error :" + ex.getMessage();
// If there is an error, don't just keep trying to
register.
// Require the user to click a button again, or
perform
// exponential back-off.
}
return msg;
}
@Override
protected void onPostExecute(String msg) {
mDisplay.append(msg + "\n");
}
}.execute(null, null, null);
...
14

iv) Send a message via


gcm.send(SENDER_ID + "@gcm.googleapis.com", id, data);

v) Recive message via registered Broadcast Reciever.


public class GcmBroadcastReceiver extends WakefulBroadcastReceiver
{
@Override
public void onReceive(Context context, Intent intent) {
// Explicitly specify that GcmIntentService will handle
the intent.
ComponentName comp = new
ComponentName(context.getPackageName(),
GcmIntentService.class.getName());
// Start the service, keeping the device awake while it is
launching.
startWakefulService(context, (intent.setComponent(comp)));
setResultCode(Activity.RESULT_OK);
}
}

vi) Pass recived message to Intent Service for payload parsing and
pertorming necessary action.
public class GcmIntentService extends IntentService {
public static final int NOTIFICATION_ID = 1;
private NotificationManager mNotificationManager;
NotificationCompat.Builder builder;
public GcmIntentService() {
super("GcmIntentService");
}
@Override
protected void onHandleIntent(Intent intent) {
Bundle extras = intent.getExtras();
GoogleCloudMessaging gcm =
GoogleCloudMessaging.getInstance(this);
// The getMessageType() intent parameter must be the
intent you received
// in your BroadcastReceiver.
String messageType = gcm.getMessageType(intent);
if (!extras.isEmpty()) {

// has effect of unparcelling


15

Bundle
/*
* Filter messages 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.
*/
if (GoogleCloudMessaging.
MESSAGE_TYPE_SEND_ERROR.equals(messageType)) {
sendNotification("Send error: " +
extras.toString());
} else if (GoogleCloudMessaging.
MESSAGE_TYPE_DELETED.equals(messageType)) {
sendNotification("Deleted messages on server: " +
extras.toString());
// If it's a regular GCM message, do some work.
} else if (GoogleCloudMessaging.
MESSAGE_TYPE_MESSAGE.equals(messageType)) {
// This loop represents the service doing some
work.
for (int i=0; i<5; i++) {
Log.i(TAG, "Working... " + (i+1)
+ "/5 @ " +
SystemClock.elapsedRealtime());
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
}
}
Log.i(TAG, "Completed work @ " +
SystemClock.elapsedRealtime());
// Post notification of received message.
sendNotification("Received: " +
extras.toString());
Log.i(TAG, "Received: " + extras.toString());
}
}
// Release the wake lock provided by the
WakefulBroadcastReceiver.
GcmBroadcastReceiver.completeWakefulIntent(intent);
}
// Put the message into a notification and post it.
// This is just one simple example of what you might choose to
do with
// a GCM message.
16

private void sendNotification(String msg) {


mNotificationManager = (NotificationManager)
this.getSystemService(Context.NOTIFICATION_SERVICE);
PendingIntent contentIntent =
PendingIntent.getActivity(this, 0,
new Intent(this, DemoActivity.class), 0);
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_stat_gcm)
.setContentTitle("GCM Notification")
.setStyle(new NotificationCompat.BigTextStyle()
.bigText(msg))
.setContentText(msg);
mBuilder.setContentIntent(contentIntent);
mNotificationManager.notify(NOTIFICATION_ID,
mBuilder.build());
}
}

5)

Write Application server


a) Implement necessary server side code to handle the payload send from
device.
b) Parse the data recieved from device and send it to GCM Server
c) Handle response of GCM Server.

6) The device would recieve message almost instantaneously.

17

PROPERTIES OF PAYLOAD
1)

The payload message sent to GCM Server is a JSON encoded string.

2)

We can send at max of 4kB of payload to GCM server.

3)

A message sent to GCM server has a lifetime of 4 weeks, that is it will reside

on GCM Server till 4 weeks or till delivered whichever comes first.


4)

Structure of a message sent to GCM Server

Content-Type:application/json
Authorization:key=AIzaSyB-1uEai2WiUapxCs2Q0GZYzPu7Udno5aA
{
"registration_id" : "APA91bHun4MxP5egoKMwt2KZFBaFUH-1RYqx...",
"data" : {
"Team" : "18",
"Score" : "3",
"Player" : "Varela",
},
}

18

POSSIBLE PROBLEMS
There may be a case that user has uninstalled the applications. Thus the
sender id we are referring to does not exit. In that case GCM server will
response back to application server that the following Id does not exist.
In that its entry from database of application server shoulb be deleted
Although Sender Id is constant for an install of application, it changes if
there is an update to the application, in that care must be taken to reregister device to GCM and also change it's Sender Id in database of
application server.
The payload limit is only 4kb, so we can not send data greater than 4kB
like genarally media files etc.

19

APPLICATIONS
GCM has the following applications:
1)

Widely used in Instant Messaging Services like Whatsapp, Hike,

Telegram etc.
2)

Used to push notifications on devices by other 3rd party applications.

20

CONCLUSION
1)

GCM stands for Google Cloud Messaging

2)

It enables to send messages to mobile devices, without using polling

in devices.
3)

Thus it does not consume much battery on devices.

4)

At most of 4kB of data can be sent using GCM.

5)

The message sent to GCM server is a JSON encoded string with keys

registration_id and data.


6)

The response sent back to 3rd party server from GCM server is also a

JSON encoded string telling about seccess and faliure of messages.


7)

There are no quota limit in GCM Service.

8)

GCM services is almost instantaneous.

9)

The message date resides on server for atmost 4 weeks if not

delievered
10) Instant messangers on Android use this service to send their
messages.
11) Other third party apps uses this services to push new notifications for
their apps.

21

REFERENCES
1)

http://developer.android.com/google/gcm/gcm.html

2)

http://developer.android.com/google/gcm/gs.html

3)

http://developer.android.com/google/gcm/client.html

4)

http://developer.android.com/google/gcm/server.html

5)

http://developer.android.com/google/gcm/notifications.html

6)

http://developer.android.com/google/gcm/adv.html

7)

http://en.wikipedia.org/wiki/Google_Cloud_Messaging

22

You might also like