Android cloud to device messaging

Android Cloud to Device Messaging (C2DM) — Tutorial

Android C2DMs. This tutorial describes how to push information from a server to the Google device. It is based on Eclipse 3.7, Java 1.6 and Android 2.3 (Gingerbread).

1. Cloud to device messaging

1.1. Polling vs. Push

Most mobile apps require data from the Internet. One approach for updating its data is that the apps periodically polls a server for new data (Polling). If no new data is available this approach uses unnecessary network bandwidth and consumes the battery of the mobile phone.

An alternative approach is that the server contacts the mobile app once new data is available (Push). If the data does not change constantly, Push is the preferred solution.

1.2. Cloud service

Via the Google Play services you can push notifications to your application. To do this you must enable Google Cloud Messaging for Android in the Google API Console.

In a C2DM you have three involved parties. The application server which wants to push messages to the Android device, Googles C2DM servers and the Android app. The program on the application server can be written in any programming language, e.g. Java, PHP, Python, etc.

When the application server needs to push a message to the Android application, it sends the message via an HTTP POST to Google’s C2DM servers.

The C2DM servers route the message to the device. If the device is not online, the message will be delivered once the device is available. Once the message is received, an Broadcast Intent is created. The mobile app has registered an Intent Receiver for this Broadcast. The app is started and processes the message via the defined Intent Receiver.

C2DM messages are limited in size to 1024 bytes and are intended to inform the device about new data not to transfer it. The typical workflow is that Googles C2DM servers notify the Android app that new data is available. Afterwards the Android app fetches the data from a different server.

Android devices maintain an connection to the Android Play server. C2DM uses this existing connections to the Google servers. This connection is highly optimize to minimize bandwidth and battery consumption.

C2DM is currently still in beta and you need to apply to use it. C2DM applies a limit of approximately 200 000 messages per sender per day and is currently free of charge.

1.3. Requirements

C2MD is available as of Android 2.2 and requires that Android Play application is installed on the device.

To use C2DM on the Android simulator you also need to use a Google device with API 8 or higher and to register with a Google account on the emulator via the Settings.

1.4. Permissions

To use C2DM in your application to have to register for the following permissions

Your application should also declare the permission «applicationPackage
«.permission.C2D_MESSAGE» with the «android:protectionLevel» of «signature» so that other applications cannot register and receive message for the application. android:protectionLevel=»signature». ensures that applications with request a permission must be signed with same certificate as the application that declared the permission.

1.5. Intent Receiver

Your application must register an intent receiver for the two intents:

The receiver for «com.google.android.c2dm.intent.RECEIVE» will be called once a new message is received, while the receiver for «com.google.android.c2dm.intent.REGISTRATION» will be called once the registration code for the app is received.

2. Implementation Steps

2.1. Application Server Registration

The application server needs to authenticate himself with the C2DM servers. Via an email and password an authentication token is determined with an HTTP POST request to the C2DM servers. The token is stored on the application server and is used to authenticate the application server with the C2DM servers once he sends out messages.

For example you can get the token for an registered email and password via the following coding:

Читайте также:  Как следить за андроидом с iphone

The token is periodically refreshed.

The above example is in Java. It is also possible to get the token via other http tools or programming languages. For example you can simulate the server via the command line tool with the tool curl.

2.2. Getting the registration ID for the mobile app

To register your Android app for the C2DM service you fire an registration intent «com.google.android.c2dm.intent.REGISTER». This will trigger a service which will send the registration to the Google C2DM servers.

The intent include an extra with the key «sender» and the email address which was registered for the C2DM service. It also must include PendingIntent with the «app» extra. The PendingIntent gives the Android system information about the current application. The value for the «sender» is the email address under which you registered your C2DM message service. Replace in the following example «youruser@gmail.com» which your email address.

The service will asynchronously register with Google and will send the «com.google.android.c2dm.intent.REGISTRATION» intent upon successful registration. Your application need to register an Broadcast Receiver for this intent. This also requires the usage of a permission based on your package as the Android system checks this internally.

The «»AndroidManifest.xml looks like the following. Please note that if you are using a different package that you have to adjust this coding.

The «com.google.android.c2dm.intent.REGISTRATION» intent includes a registration ID. Each registration ID represents a particular device, e.g. every Android phone will receive its own registration code.

The C2DM may refresh this registration ID periodically but until a refreshment your application should store this ID for later use.

After the Android app received the registration ID it has to send this information to the application server. The application server can use the registration ID to send a message to the device via the C2DM servers from Google.

For example the following code sends the deviceId and the registrationId to a server.

The server uses some persistence to store the registration IDs.

2.3. Register Receiver for C2DM messages

Similar to registration of the registration receiver you need to configure a message receiver. This could be the same or a different receiver than the registration receiver. The following shows an example of an separate message receiver.

In addition you need to register the message receiver in your AndroidManifest.xml file.

2.4. Send messages

At this point your application server and your Android app are ready to use C2DM. Your server has his authentication token and the registration ID of the app. And the mobile app has registered Broadcast Receiver for receiving the message.

To send a message to a device, the application server sends a HTTP POST request to the Google C2DM servers. This HTTP GET request contains the registration ID for this device and well as the authentication token (to tell Google that this server is allowed to send messages).

Once your server sends the message to the C2DM server this server will queue the message until the device is available. The message will be send to the device as a broadcast. Your application needs to register for this broadcast event to receive the message.

A received message is send to the registered broadcast receiver for «com.google.android.c2dm.intent.RECEIVE». The data can be received from the Intent via getExtras(). The available keys are «payload», «from», «collapse_key». The actual data is included in «payload». The receiver can extracts this data and can react to it.

3. Device and Registration

Currently C2DM is under beta testing. You need to ask for access. Here is the link to the signup form.

If you test the following example on the emulator make sure that you use Google API 8 or later. You also have to register a Google user on the virtual device under Settings Accounts Sync .

If you test the following example on a real device make sure that the Android Market is installed.

4. Tutorial: Create your C2DM enabled application

4.1. Project and Layout

Create the Android project «de.vogella.android.c2dm.simpleclient» with the activity «C2DMClientActivity». Create the following layout main.xml .

Also create the layout «activity_result.xml» which we will use in our result activities.

4.2. Create receivers and activities

Create the following class «C2DMReceiverReceiver» and «C2DMMessageReceiver» which we will later registers as receivers for the registration intent and the message intent.

Also create the following two Activities which we will use to see the results.

Create the following AndroidManifest.xml file. That will register the Intent Receivers, Activities and requests the required permissions.

Change your «C2DMClientActivity» class to the following.

The methods in the activity are connected to the buttons via the onclick property of the buttons. The first button triggers a request for a registration ID and the second button shows the saved registration key. Both also write the registration id also to the Logcat View.

Читайте также:  Как сделать actionbar android

Copy the registration Id from the Logcat View so that you can later use it in your server implementation.

4.3. Register your application

Run your application, maintain your registered user and press the button. Check LogCat for the registration ID.

If you see the following message:

Make sure you are using a Google device and that you have a Google user registered on the device.

5. Tutorial: Using command line tool curl to simulator the server

If you run a Linux system you can easily test the service on the command line. You can request your authentication key via curl on the command line. From the response get the part after «Auth=».

This part and the registration code can be used to send a message to your device.

6. Tutorial: Create your server application

As described earlier the application server needs to get an authentication key via HTTPS. Afterwards it can send messages to the device via HTTP by supplying the authentication key and the registration ID.

We will simulate the Server via a Java program. The registration ID of the device will be hard-coded into this app as we do not have the possibility to reach this app via http. Keep in mind that this is only an example to make it simple to test C2DM.

To store you credentials use the following class.

Create a new Java project «de.vogella.java.c2dm.server». Create the following class. This class is an utility class to get the authentication token from the Google server.

Create the following class «GetAuthenticationToken». This class can be used to get the authentication token.

Run your GetAuthenticationToken class and copy the authentication token from the command line.

Create the following class and maintain your authentication token and your registration id.

Also create the following utility class which will allow to send messages to your device.

Finally create the following class «SendMessageToDevice» which can send messages to your device.

Run it. This should send a message to your device and give you the return code «200». On your device you should see a notification and if you open it you should see the message displayed.

Источник

Android Cloud to Device Messaging

Motivation

A project I’ve always had working in some form is a method of notifications from IRC on my phone. This, through bitlbee, also includes my instant messaging and twitter notifications. All of these solutions have been quick hacks, and I felt it wa time to write a speedy My previous solution was to forward any hilights over XMPP to receive notifications in google talk on my android phone. However this soon proved too much of an annoyance and notifications weren’t delivered as fast as I wanted. I’ve called my new solution generic_notify which I hope to be able to use like notify_send to send any sort of notification on the command line and have it appear on my phone.

C2DM basics

Android 2.2 “Froyo” introduced Cloud to Device Messaging (c2dm), a service to send small amounts of data to an android phone. It works by having the application register with the service and then having a remote server send a message to the c2dm google API, which is then forwarded to the device. A good reference and example application is chrometophone.

Currently, signing up for c2dm is required with the account used to send the messages.

Manifest

I used the com.google.android.c2dm library which can be found in the chrometophone source code. AndroidManifest.xml will need to be modified slightly to use it.

versionCode and versionName are set to these values since c2dm is for android 2.2 and up.

A couple of permissions are also needed

android:name= «com.johnhawthorn.generic_notify.permission.C2D_MESSAGE» android:protectionLevel= «signature»/> android:name= «com.johnhawthorn.generic_notify.permission.C2D_MESSAGE»/> android:name= «com.google.android.c2dm.permission.RECEIVE»/> android:name= «android.permission.WAKE_LOCK»/> android:name= «android.permission.GET_ACCOUNTS»/> android:name= «android.permission.USE_CREDENTIALS»/>

And the following inside the application declaration

Declaring the receiver

A class named C2DMReceiver needs to be declared which the com.google.android.c2dm library will call.

Next a couple methods are needed

onRegistered is called registration with the c2dm service is successful. The registration key is received here and is usually sent to a server but for now it’s enough to log the key.

onMessage should also be declared which is called whenever a message is received.

Finally onError should deal with any errors.

Registering

Registering with the c2dm service is done by calling C2DMessaging.register . Registration needs only needs to be done the first time an application is run. Messages are received even when the application is not running and registration will persist across reboot

Читайте также:  Как взломать вай фай с андроида без рут прав

Testing

I tested by running the application and grabbing the registration id out of the logs. You can then grab a google ClientLogin Auth Token for the ac2dm service and then send messages using curl.

Источник

Обмен сообщениями между облаком и устройством (Cloud to Device Messaging)

Характеристики Android сервиса C2DM

Главные характеристики C2DM:
  1. Он позволяет сторонним серверам приложений отправлять небольшие сообщения своим Android приложениям. Сервис обмена сообщениями не предназначен для отправки большого количества пользовательских данных через сообщения. Напротив, он должен использоваться для сообщения приложению, что есть новые данные на сервере, и что приложение может забрать их.
  2. Приложение на Android устройстве не нужно запускать для получения сообщений. Система запустит приложение через целевую трансляцию, когда придет сообщение, если приложение установлено с соответствующими приемником трансляции и разрешениями.
  3. Он использует существующее соединение для сервисов Google. Это требует от пользователей установки учетной записи Google на их мобильных устройствах.

Обзор архитектуры

Обмен сообщениями между облаком и устройством включает ключевые термины и понятия, которые могут быть классифицированы на два подразделения. Это:

  1. Компоненты
  2. Верительные данные

Верительные данные

Идентификаторы и токены, которые используются на различных стадиях C2DM для обеспечения того, чтобы все стороны были авторизованы, и чтобы сообщение направлялось в правильное место.

Идентификатор отправителя (Sender ID)

Это электронная почта учетной записи, связанной с разработчиком приложения. Идентификатор отправителя используется в процессе регистрации для идентификации Android приложения, которому разрешается отправлять сообщения на устройство. Этот идентификатор, как правило, основывается на роли, а не на персональной учетной записи, например, my-app@gmail.com

Идентификатор приложения (Application ID)

Это идентификатор приложения, которое регистрируется для получения сообщений. Приложение определяется по имени пакета из манифеста (manifest). Это гарантирует, что сообщения нацелены на правильное приложение.

Регистрационный идентификатор (Registration ID)

Идентификатор, выданный C2DM серверами Android приложению, позволяющий ему получать сообщения. Как только приложение получает регистрационный идентификатор, оно отправляет его стороннему серверу приложений, который использует его для идентификации каждого устройства, которое зарегистрировалось для получения сообщений для данного приложения. Другими словами, регистрационный идентификатор привязан к определенному приложению, запущенному на определенном устройстве. Чтобы работала учетная запись Google для C2DM, мобильное устройство должно включать хотя бы одну авторизованную учетную запись Google.

Токен аутентификации отправителя (Sender Auth Token)

ClientLoginAuth токен, который сохраняется на стороннем сервере приложений и дает серверу приложений авторизованный доступ к сервисам Google. Токен включен в заголовок POST запросов, которые отправляют сообщения.

Жизненный цикл C2DM

Основные процессы, используемые в обмене сообщениями между облаком и устройством:

  1. Включение C2DM: Android приложение, запущенное на мобильном устройстве, регистрируется для получения сообщений.
  2. Отправка сообщения: сторонний сервер приложений отправляет сообщения на устройство.
  3. Получение сообщения: Android приложение получает сообщение от C2DM сервера.

Включение C2DM

Ниже приведена последовательность событий, которые возникают, когда Android приложение, запущенное на мобильном устройстве, регистрируется для получения сообщений:

  1. Первый раз, когда приложение должно использовать сервис обмена сообщениями, оно посылает запрос регистрации C2DM серверу.
    Этот запрос регистрации включает идентификатор отправителя (это учетная запись авторизованная для отправки сообщений приложению, которая, как правило, является адресом электронной почты учетной записи, настроенной разработчиком приложения) и идентификатор приложения.
  2. C2DM сервер транслирует запрос, который дает приложению регистрационный идентификатор.
    Приложение хранит этот идентификатор для дальнейшего использования. Google может периодически обновлять регистрационный идентификатор, поэтому приложение разработано с учетом того, что запрос регистрации (registration intent) может быть вызван несколько раз.
  3. Чтобы завершить регистрацию, приложение отправляет регистрационный идентификатор серверу приложений. Сервер приложений, как правило, хранит регистрационный идентификатор в базе данных.
    Регистрационный идентификатор действует, пока приложение само не отменит регистрацию или пока Google не обновит регистрационный идентификатор для Вашего приложения.

Отправка сообщения

Чтобы сервер приложений отправлял сообщения, должны быть выполнены следующие условия:

  1. Наличие регистрационного идентификатора у приложения, который позволяет ему получать сообщения для определенного устройства.
  2. Регистрационный идентификатор хранится на сервере приложений.

Существует еще одно условие, которое необходимо для того, чтобы сервер приложений мог отправлять сообщения: Client Login authorization токен. Client Login токен авторизует сервер приложений для отправки сообщений определенному Android приложению. Сервер приложений имеет один Client Login токен для конкретного стороннего приложения и несколько регистрационных идентификаторов. Каждый регистрационный идентификатор представляет конкретное устройство, которое зарегистрировалось для использования сервиса обмена сообщениями для конкретного стороннего приложения.

Последовательность событий, которые возникают, когда сервер приложений отправляет сообщение:

  1. Сервер приложений отправляет сообщение C2DM серверам.
  2. Google ставит в очередь и сохраняет сообщение в случае, если устройство неактивно.
  3. Если устройство находится онлайн, Google отправляет сообщение устройству.
  4. На устройстве система транслирует сообщение определенному приложению через целевую трансляцию с соответствующими разрешениями, так что только целевое приложение получит сообщение. Это запускает приложение. Приложение не требует предварительного запуска для получения сообщения.
  5. Приложение обрабатывает сообщение. Если приложение осуществляет нетривиальную обработку, возможно, Вы захотите воспользоваться wake lock и сделать любую обработку в сервисе.

Приложение может отменить регистрацию C2DM, если у него больше нет необходимости получать сообщения.

Источник

Оцените статью