SlideShare a Scribd company logo
Android Cloud
  to Device
 Messaging
 Framework
Android Cloud to Device Messaging Framework at GTUG Stockholm
"It allows third-party application servers
to send lightweight messages to their
Android applications"
Not designed to send a lot of content via messages. Instead
use C2DM to tell the application that there is new data on the
server to fetch.
"C2DM makes no guarantees about
delivery or the order of messages"
Eg. not suitable for instant messaging, instead use C2DM to
notify the user that there is new messages.
"An application on an Android device
doesn’t need to be running to receive
messages"
Intent broadcast wake up the app
"It does not provide any built-in user
interface or other handling for message
data"
Passes raw message data. You are free to do whatever you
want with the data. Fire a notification, send SMS, start another
application etc.
"It requires devices running Android 2.2
or higher that also have the Market
application installed"
Market is needed for technical reasons. No need to distribute
via Market.
"It uses an existing connection for
Google services"
Requires the user to be logged in with a Google Account on the
device.
Establish connection
                   with conn servers



                                                   Send to conn
                               Send to             servers
                               device
                                                                  Stores message




                                                       App server sends
                                                       HTTP POST
                                                       Google




http://code.google.com/events/io/2010/sessions/push-applications-android.html
Lifecycle

  Register device
  App server send message
  Device receives message
  Unregister device
Register device

  App fires off Intent to register with Google
  com.google.android.c2dm.intent.REGISTER
  App receives Intent with registration ID from Google
  com.google.android.c2dm.intent.REGISTRATION
  App sends registration ID to app server
Register device
// Intent to register
Intent regIntent = new
  Intent("com.google.android.c2dm.intent.REGISTER");

// Identifies the app
regIntent.putExtra("app",
  PendingIntent.getBroadcast(context, 0, new Intent(), 0));

// Identifies the role account, same as used when sending
regIntent.putExtra("sender", senderEmail);

// Start registration process
context.startService(regIntent);
Register device
public void onReceive(Context context, Intent intent) {
  if (intent.getAction().equals("...REGISTRATION")) {
    handleRegistration(context, intent);
  }
}

private void handleRegistration(Context context, Intent intent) {
  String registration = intent.getStringExtra("registration_id");
  if (intent.getStringExtra("error") != null) {
    // Registration failed, should try again later.
  } else if (intent.getStringExtra("unregistered") != null) {
    // unregistration done
  } else if (registration != null) {
    // Send the registration ID to app server
    // This should be done in a separate thread.
    // When done, remember that all registration is done.
  }
}
Unregister device


  App fires off a unregister Intent to register with Google com.
  google.android.c2dm.intent.UNREGISTER
  App tells app server to remove the stored registration ID
<manifest ...
  <application ...
    <service android:name=".C2DMReceiver" />
    <receiver android:name="com.google.android.c2dm.C2DMBroadcastReceiv
      <intent-filter>
        <action android:name="com.google.android.c2dm.intent.RECEIVE" /
        <category android:name="com.markupartist.sthlmtraveling" />
      </intent-filter>
      <intent-filter>
        <action android:name="com.google.android.c2dm.intent.REGISTRATI
        <category android:name="com.markupartist.sthlmtraveling" />
      </intent-filter>
    </receiver>
  </application>
  <uses-sdk android:minSdkVersion="3" android:targetSdkVersion="8" />
  <permission android:name="com.markupartist.sthlmtraveling.permission.
android:protectionLevel="signature" />
  <uses-permission android:name="com.markupartist.sthlmtraveling.permis
C2D_MESSAGE" />
  <uses-permission android:name="com.google.android.c2dm.permission.REC
  <uses-permission android:name="android.permission.INTERNET" />
</manifest>
<manifest ...
  <application ...
    <service android:name=".C2DMReceiver" />
    <receiver android:name="com.google.android.c2dm.C2DMBroadcastReceive
      <intent-filter>
        <action android:name="com.google.android.c2dm.intent.RECEIVE" />
        <category android:name=" com.markupartist.sthlmtraveling " />
      </intent-filter>
      <intent-filter>
        <action android:name="com.google.android.c2dm.intent.REGISTRATIO
        <category android:name=" com.markupartist.sthlmtraveling " />
      </intent-filter>
    </receiver>
  </application>
  <uses-sdk android:minSdkVersion="3" android:targetSdkVersion="8" />
  <permission android:name=" com.markupartist.sthlmtraveling .permission.
android:protectionLevel="signature" />
  <uses-permission android:name=" com.markupartist.sthlmtraveling .permis
C2D_MESSAGE" />
  <uses-permission android:name="com.google.android.c2dm.permission.RECE
  <uses-permission android:name="android.permission.INTERNET" />
</manifest>
Send message
From the documentation:
For an application server to send a message, the following
things must be in place:
    The application has a registration ID that allows it to receive
    messages for a particular device.
    The third-party application server has stored the registration
    ID.
There is one more thing that needs to be in place for the
application server to send messages: a ClientLogin
authorization token. This is something that the developer must
have already set up on the application server for the
application (for more discussion, see Role of the Third-Party
Application Server). Now it will get used to send messages to
the device.
http://code.google.com/android/c2dm/index.html#lifecycle
Send message
   Retrieve ac2dm auth token (put on app server)
   Send authenticated POST
   - GoogleLogin auth=<TOKEN>
   - URL Encoded parameters
      registration_id
      collapse_key
      deplay_while_idle - optional
      data.<KEY> - optional


Using cURL to interact with Google Data services:

http://code.google.com/apis/gdata/articles/using_cURL.html
ac2dm authorization token

curl https://www.google.com/accounts/ClientLogin 
-d Email=<ACCOUNT_EMAIL> -d Passwd=<PASSWORD> 
-d accountType=HOSTED_OR_GOOGLE 
-d source=markupartist-sthlmtraveling-1 
-d service=ac2dm

SID=DQAAA...
LSID=DQAAA...
Auth=DQAAA...
Token can change

URL url = new URL(serverConfig.getC2DMUrl());
HttpURLConnection conn =
    (HttpURLConnection) url.openConnection();
...
// Check for updated token header
String updatedAuthToken =
    conn.getHeaderField("Update-Client-Auth");
if (updatedAuthToken != null &&
    !authToken.equals(updatedAuthToken)) {
  serverConfig.updateToken(updatedAuthToken);
}
Send message
curl https://android.apis.google.com/c2dm/send 
-d registration_id=<REGISTRATION ID> 
-d collapse_key=foo 
-d data.key1=bar 
-d delay_while_idle=1 
-H "Authorization: GoogleLogin auth=<AUTH TOKEN>"


Response codes
   200 OK
   - id=<MESSAGE ID> of sent message, success
   - Error=<ERROR CODE>, failed to send
   401 Not Authorized
   503 Service Unavailable, retry
collapse_key

 Only the latest message with the same key will be delivered
 Avoids multiple messages of the same type to be delivered
 to an offline device
 State should be in app server and not in the message
 Eg. could be the URL to fetch data from
delay_while_idle

  Message is not immediately sent to the device if it is idle
Receive a message
  Device receives the message and converts it to Intent
  - com.google.android.c2dm.intent.RECEIVE
  App wakes up to handle Intent
  - data.<KEY> is translated to extras

curl https://android.apis.google.com/c2dm/send 
...
-d data.key1=bar 
...

protected void onReceive(Context context, Intent intent) {
  if (intent.getAction().equals("...RECEIVE")) {
    String key1 = intent.getExtras().getString("key1");
    // If starting another intent here remember to set the
    // flag FLAG_ACTIVITY_NEW_TASK
  }
}
Chrome to phone

http://code.google.
com/p/chrometophone/source/browse/#svn/trunk/android/c2dm
/com/google/android/c2dm
C2DMessaging.register(context, "Role account
email");


C2DMessaging.unregister(context);
public class C2DMReceiver extends C2DMBaseReceiver {
     public C2DMReceiver() {
         super("Role account email");
     }
     @Override
     public void onRegistrered(Context context, String registration) {
         // Handle registrations
     }
     @Override
     public void onUnregistered(Context context) {
         // Handle unregistered
     }
     @Override
     public void onError(Context context, String errorId) {
         // Handle errors
     }
     @Override
     public void onMessage(Context context, Intent intent) {
         // Handle received message.
   }
}
Problems

 Can't send message to device if logged in with the role
 account
References

 http://code.google.com/android/c2dm/
 http://code.google.com/events/io/2010/sessions/push-
 applications-android.html
 http://code.google.com/p/chrometophone/
Demo

http://screenr.com/QDn

http://screenr.com/ovn

More Related Content

PDF
FOSS STHLM Android Cloud to Device Messaging
PDF
android level 3
PDF
Paul Lammertsma: Account manager & sync
PDF
ASPNET_MVC_Tutorial_06_CS
ODP
OpenWebBeans/Web Beans
PDF
A Detailed Guide to Securing React applications with Keycloak - WalkingTree ...
PPTX
Esquema de pasos de ejecución IdM
PDF
Stateless Auth using OAuth2 & JWT
FOSS STHLM Android Cloud to Device Messaging
android level 3
Paul Lammertsma: Account manager & sync
ASPNET_MVC_Tutorial_06_CS
OpenWebBeans/Web Beans
A Detailed Guide to Securing React applications with Keycloak - WalkingTree ...
Esquema de pasos de ejecución IdM
Stateless Auth using OAuth2 & JWT

What's hot (20)

PPTX
Android+ax+app+wcf
PDF
Jasigsakai12 columbia-customizes-cas
DOCX
Android ax app wcf
PPTX
An Introduction to OAuth2
PPTX
OAuth 2 Presentation
PPTX
Oauth 2.0 security
PDF
Android securitybyexample
PPTX
16 interacting with user data contacts and appointments
PDF
24032022 Zero Trust for Developers Pub.pdf
ODP
OAuth2 - Introduction
PPT
Lviv MDDay 2014. Сергій Комлач “Використання accessibility api для доступу до...
PDF
OAuth2 and Spring Security
PPTX
Use Windows Azure Service Bus, BizTalk Services, Mobile Services, and BizTalk...
PPTX
OAuth 2
PDF
Intro to API Security with Oauth 2.0
PDF
EmberConf 2015 – Ambitious UX for Ambitious Apps
PPTX
Securing the Web@VoxxedDays2017
PPT
OpenSocial Intro
PDF
Stateless authentication for microservices
PPTX
OAuth 2.0 - The fundamentals, the good , the bad, technical primer and commo...
Android+ax+app+wcf
Jasigsakai12 columbia-customizes-cas
Android ax app wcf
An Introduction to OAuth2
OAuth 2 Presentation
Oauth 2.0 security
Android securitybyexample
16 interacting with user data contacts and appointments
24032022 Zero Trust for Developers Pub.pdf
OAuth2 - Introduction
Lviv MDDay 2014. Сергій Комлач “Використання accessibility api для доступу до...
OAuth2 and Spring Security
Use Windows Azure Service Bus, BizTalk Services, Mobile Services, and BizTalk...
OAuth 2
Intro to API Security with Oauth 2.0
EmberConf 2015 – Ambitious UX for Ambitious Apps
Securing the Web@VoxxedDays2017
OpenSocial Intro
Stateless authentication for microservices
OAuth 2.0 - The fundamentals, the good , the bad, technical primer and commo...
Ad

Similar to Android Cloud to Device Messaging Framework at GTUG Stockholm (20)

PPTX
Android cloud to device messaging
 
PPTX
Android Cloud To Device Messaging
PDF
Android push-applications-android
PDF
Android Cloud2Device Messaging
PPTX
PDF
勝手に改造 Chrome to Phone
PPTX
Android Cloud to Device Messaging with the Google App Engine
PPTX
Gcm presentation
PPT
Android C2DM Presentation at O'Reilly AndroidOpen Conference
PPTX
Introduction to google cloud messaging in android
PDF
Push to Me: Mobile Push Notifications (Zend Framework)
PPTX
AC2DM For Security
PPTX
GCM Technology for Android
PDF
GCM for Android
PDF
PPTX
Android™ application development
PPTX
AutoMate+
PPT
Android Cloud to Device Messaging Framework
Android cloud to device messaging
 
Android Cloud To Device Messaging
Android push-applications-android
Android Cloud2Device Messaging
勝手に改造 Chrome to Phone
Android Cloud to Device Messaging with the Google App Engine
Gcm presentation
Android C2DM Presentation at O'Reilly AndroidOpen Conference
Introduction to google cloud messaging in android
Push to Me: Mobile Push Notifications (Zend Framework)
AC2DM For Security
GCM Technology for Android
GCM for Android
Android™ application development
AutoMate+
Android Cloud to Device Messaging Framework
Ad

More from Johan Nilsson (10)

PDF
Utmaningar som tredjepartsutvecklare för kollektivtrafikbranchen - Kollektivt...
PDF
GTFS & OSM in STHLM Traveling at Trafiklab
PDF
STHLM Traveling Trafiklab
PDF
JavaScript Dependencies, Modules & Browserify
PDF
Spacebrew & Arduino Yún
PDF
Trafiklab 1206
PDF
Custom UI Components at Android Only 2011
PPT
new Android UI Patterns
PDF
Android swedroid
PPT
GTUG Android iglaset Presentation 1 Oct
Utmaningar som tredjepartsutvecklare för kollektivtrafikbranchen - Kollektivt...
GTFS & OSM in STHLM Traveling at Trafiklab
STHLM Traveling Trafiklab
JavaScript Dependencies, Modules & Browserify
Spacebrew & Arduino Yún
Trafiklab 1206
Custom UI Components at Android Only 2011
new Android UI Patterns
Android swedroid
GTUG Android iglaset Presentation 1 Oct

Recently uploaded (20)

PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PDF
Approach and Philosophy of On baking technology
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PDF
cuic standard and advanced reporting.pdf
PPTX
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
PDF
Empathic Computing: Creating Shared Understanding
PPT
Teaching material agriculture food technology
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PDF
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
DOCX
The AUB Centre for AI in Media Proposal.docx
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PDF
Network Security Unit 5.pdf for BCA BBA.
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
PPTX
Understanding_Digital_Forensics_Presentation.pptx
20250228 LYD VKU AI Blended-Learning.pptx
Advanced methodologies resolving dimensionality complications for autism neur...
The Rise and Fall of 3GPP – Time for a Sabbatical?
Approach and Philosophy of On baking technology
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
cuic standard and advanced reporting.pdf
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
Empathic Computing: Creating Shared Understanding
Teaching material agriculture food technology
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
Digital-Transformation-Roadmap-for-Companies.pptx
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
The AUB Centre for AI in Media Proposal.docx
Reach Out and Touch Someone: Haptics and Empathic Computing
Per capita expenditure prediction using model stacking based on satellite ima...
Network Security Unit 5.pdf for BCA BBA.
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
Understanding_Digital_Forensics_Presentation.pptx

Android Cloud to Device Messaging Framework at GTUG Stockholm

  • 1. Android Cloud to Device Messaging Framework
  • 3. "It allows third-party application servers to send lightweight messages to their Android applications" Not designed to send a lot of content via messages. Instead use C2DM to tell the application that there is new data on the server to fetch.
  • 4. "C2DM makes no guarantees about delivery or the order of messages" Eg. not suitable for instant messaging, instead use C2DM to notify the user that there is new messages.
  • 5. "An application on an Android device doesn’t need to be running to receive messages" Intent broadcast wake up the app
  • 6. "It does not provide any built-in user interface or other handling for message data" Passes raw message data. You are free to do whatever you want with the data. Fire a notification, send SMS, start another application etc.
  • 7. "It requires devices running Android 2.2 or higher that also have the Market application installed" Market is needed for technical reasons. No need to distribute via Market.
  • 8. "It uses an existing connection for Google services" Requires the user to be logged in with a Google Account on the device.
  • 9. Establish connection with conn servers Send to conn Send to servers device Stores message App server sends HTTP POST Google http://code.google.com/events/io/2010/sessions/push-applications-android.html
  • 10. Lifecycle Register device App server send message Device receives message Unregister device
  • 11. Register device App fires off Intent to register with Google com.google.android.c2dm.intent.REGISTER App receives Intent with registration ID from Google com.google.android.c2dm.intent.REGISTRATION App sends registration ID to app server
  • 12. Register device // Intent to register Intent regIntent = new Intent("com.google.android.c2dm.intent.REGISTER"); // Identifies the app regIntent.putExtra("app", PendingIntent.getBroadcast(context, 0, new Intent(), 0)); // Identifies the role account, same as used when sending regIntent.putExtra("sender", senderEmail); // Start registration process context.startService(regIntent);
  • 13. Register device public void onReceive(Context context, Intent intent) { if (intent.getAction().equals("...REGISTRATION")) { handleRegistration(context, intent); } } private void handleRegistration(Context context, Intent intent) { String registration = intent.getStringExtra("registration_id"); if (intent.getStringExtra("error") != null) { // Registration failed, should try again later. } else if (intent.getStringExtra("unregistered") != null) { // unregistration done } else if (registration != null) { // Send the registration ID to app server // This should be done in a separate thread. // When done, remember that all registration is done. } }
  • 14. Unregister device App fires off a unregister Intent to register with Google com. google.android.c2dm.intent.UNREGISTER App tells app server to remove the stored registration ID
  • 15. <manifest ... <application ... <service android:name=".C2DMReceiver" /> <receiver android:name="com.google.android.c2dm.C2DMBroadcastReceiv <intent-filter> <action android:name="com.google.android.c2dm.intent.RECEIVE" / <category android:name="com.markupartist.sthlmtraveling" /> </intent-filter> <intent-filter> <action android:name="com.google.android.c2dm.intent.REGISTRATI <category android:name="com.markupartist.sthlmtraveling" /> </intent-filter> </receiver> </application> <uses-sdk android:minSdkVersion="3" android:targetSdkVersion="8" /> <permission android:name="com.markupartist.sthlmtraveling.permission. android:protectionLevel="signature" /> <uses-permission android:name="com.markupartist.sthlmtraveling.permis C2D_MESSAGE" /> <uses-permission android:name="com.google.android.c2dm.permission.REC <uses-permission android:name="android.permission.INTERNET" /> </manifest>
  • 16. <manifest ... <application ... <service android:name=".C2DMReceiver" /> <receiver android:name="com.google.android.c2dm.C2DMBroadcastReceive <intent-filter> <action android:name="com.google.android.c2dm.intent.RECEIVE" /> <category android:name=" com.markupartist.sthlmtraveling " /> </intent-filter> <intent-filter> <action android:name="com.google.android.c2dm.intent.REGISTRATIO <category android:name=" com.markupartist.sthlmtraveling " /> </intent-filter> </receiver> </application> <uses-sdk android:minSdkVersion="3" android:targetSdkVersion="8" /> <permission android:name=" com.markupartist.sthlmtraveling .permission. android:protectionLevel="signature" /> <uses-permission android:name=" com.markupartist.sthlmtraveling .permis C2D_MESSAGE" /> <uses-permission android:name="com.google.android.c2dm.permission.RECE <uses-permission android:name="android.permission.INTERNET" /> </manifest>
  • 17. Send message From the documentation: For an application server to send a message, the following things must be in place: The application has a registration ID that allows it to receive messages for a particular device. The third-party application server has stored the registration ID. There is one more thing that needs to be in place for the application server to send messages: a ClientLogin authorization token. This is something that the developer must have already set up on the application server for the application (for more discussion, see Role of the Third-Party Application Server). Now it will get used to send messages to the device. http://code.google.com/android/c2dm/index.html#lifecycle
  • 18. Send message Retrieve ac2dm auth token (put on app server) Send authenticated POST - GoogleLogin auth=<TOKEN> - URL Encoded parameters registration_id collapse_key deplay_while_idle - optional data.<KEY> - optional Using cURL to interact with Google Data services: http://code.google.com/apis/gdata/articles/using_cURL.html
  • 19. ac2dm authorization token curl https://www.google.com/accounts/ClientLogin -d Email=<ACCOUNT_EMAIL> -d Passwd=<PASSWORD> -d accountType=HOSTED_OR_GOOGLE -d source=markupartist-sthlmtraveling-1 -d service=ac2dm SID=DQAAA... LSID=DQAAA... Auth=DQAAA...
  • 20. Token can change URL url = new URL(serverConfig.getC2DMUrl()); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); ... // Check for updated token header String updatedAuthToken = conn.getHeaderField("Update-Client-Auth"); if (updatedAuthToken != null && !authToken.equals(updatedAuthToken)) { serverConfig.updateToken(updatedAuthToken); }
  • 21. Send message curl https://android.apis.google.com/c2dm/send -d registration_id=<REGISTRATION ID> -d collapse_key=foo -d data.key1=bar -d delay_while_idle=1 -H "Authorization: GoogleLogin auth=<AUTH TOKEN>" Response codes 200 OK - id=<MESSAGE ID> of sent message, success - Error=<ERROR CODE>, failed to send 401 Not Authorized 503 Service Unavailable, retry
  • 22. collapse_key Only the latest message with the same key will be delivered Avoids multiple messages of the same type to be delivered to an offline device State should be in app server and not in the message Eg. could be the URL to fetch data from
  • 23. delay_while_idle Message is not immediately sent to the device if it is idle
  • 24. Receive a message Device receives the message and converts it to Intent - com.google.android.c2dm.intent.RECEIVE App wakes up to handle Intent - data.<KEY> is translated to extras curl https://android.apis.google.com/c2dm/send ... -d data.key1=bar ... protected void onReceive(Context context, Intent intent) { if (intent.getAction().equals("...RECEIVE")) { String key1 = intent.getExtras().getString("key1"); // If starting another intent here remember to set the // flag FLAG_ACTIVITY_NEW_TASK } }
  • 26. public class C2DMReceiver extends C2DMBaseReceiver { public C2DMReceiver() { super("Role account email"); } @Override public void onRegistrered(Context context, String registration) { // Handle registrations } @Override public void onUnregistered(Context context) { // Handle unregistered } @Override public void onError(Context context, String errorId) { // Handle errors } @Override public void onMessage(Context context, Intent intent) { // Handle received message. } }
  • 27. Problems Can't send message to device if logged in with the role account