Google cloud messaging report

December 7, 2016 | Author: Vineet Garg | Category: N/A
Share Embed Donate


Short Description

A short report on google cloud messaging...

Description

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

2

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

3

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.

4

INDEX S.No

Topic

Page no.

1

Introduction

6

2

Key Concepts

7

3

Architectural Overview

9

4

Lifecycle Flow

10

5

Implementing Gcm Service

12

6

Properties of Payload

18

7

Possible Problems

19

8

Applications

20

9

Conclusion

21

10

References

22

5

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 don’t 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.

6

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

7

Token

application server authorized access to Google services. The API key is included in the header of POST requests that send messages.

8

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.

9

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
View more...

Comments

Copyright ©2017 KUPDF Inc.
SUPPORT KUPDF