SlideShare ist ein Scribd-Unternehmen logo
1 von 42
Downloaden Sie, um offline zu lesen
Android Cloud
to Device
Messaging
Framework
How to keep data fresh?
Polling
Simple to implement
Ask for data periodically
Radio draws a lot of power
Pushing
Harder to implement
Less battery consumption
Only uses network when needed
Constant connection
Components
Intent
Description of an action to perform
BroadcastReceiver
Recieve intents
IntentService
Handles asynchronous request, started when needed
WakeLock
Wake up the device at desired level
AlarmManager
Schedule the app to run in the future
Synchronize polls with INTERVAL_*
Some interesting projects
CouchOne Mobile for Android
http://www.couch.io/android
Ericsson Labs - Mobile Push
https://labs.ericsson.com/apis/mobile-push/
Whoopingkof - Evented Sockets
http://github.com/voltron/whoopingkof/
"It allows third-party
application servers to
send lightweight messages
to their Android
applications"
"C2DM makes no
guarantees about delivery
or the order of messages"
"An application on an
Android device doesn’t
need to be running to
receive messages"
"It does not provide any
built-in user interface or
other handling for
message data"
"It requires devices
running Android 2.2 or
higher that also have the
Market application
installed"
"It uses an existing
connection for Google
services"
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
Send message
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.
http://code.google.com/android/c2dm/index.html#lifecycle
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.
From the documentation:
Send message
Retrieve ac2dm auth token (put on app server)
Send authenticated POST
- GoogleLogin auth=<TOKEN>
- URL Encoded parameters
registration_id
collapse_key
delay_while_idle - optional
data.<KEY> - optional
Using cURL to interact with Google Data services:
http://code.google.com/apis/gdata/articles/using_cURL.html
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
ac2dm authorization token
SID=DQAAA...
LSID=DQAAA...
Auth=DQAAA...
Service
name for
C2DM
Authorizatio
n token
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);
}
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>"
Send message
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
Receive a message
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
}
}
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
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
401
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

Weitere ähnliche Inhalte

Was ist angesagt?

Using ArcGIS with OAuth 2.0 - Esri DevSummit Dubai 2013
Using ArcGIS with OAuth 2.0 - Esri DevSummit Dubai 2013Using ArcGIS with OAuth 2.0 - Esri DevSummit Dubai 2013
Using ArcGIS with OAuth 2.0 - Esri DevSummit Dubai 2013
Aaron Parecki
 

Was ist angesagt? (20)

Stateless authentication for microservices
Stateless authentication for microservicesStateless authentication for microservices
Stateless authentication for microservices
 
OAuth2 - Introduction
OAuth2 - IntroductionOAuth2 - Introduction
OAuth2 - Introduction
 
OAuth 2
OAuth 2OAuth 2
OAuth 2
 
Infra Project report2
Infra Project report2Infra Project report2
Infra Project report2
 
WAC Widget Upload Process
WAC Widget Upload ProcessWAC Widget Upload Process
WAC Widget Upload Process
 
An Introduction to OAuth2
An Introduction to OAuth2An Introduction to OAuth2
An Introduction to OAuth2
 
Android CI and Appium
Android CI and AppiumAndroid CI and Appium
Android CI and Appium
 
OAuth2 and Spring Security
OAuth2 and Spring SecurityOAuth2 and Spring Security
OAuth2 and Spring Security
 
Intro to API Security with Oauth 2.0
Intro to API Security with Oauth 2.0Intro to API Security with Oauth 2.0
Intro to API Security with Oauth 2.0
 
Using ArcGIS with OAuth 2.0 - Esri DevSummit Dubai 2013
Using ArcGIS with OAuth 2.0 - Esri DevSummit Dubai 2013Using ArcGIS with OAuth 2.0 - Esri DevSummit Dubai 2013
Using ArcGIS with OAuth 2.0 - Esri DevSummit Dubai 2013
 
OAuth2 + API Security
OAuth2 + API SecurityOAuth2 + API Security
OAuth2 + API Security
 
Adding User Management to Node.js
Adding User Management to Node.jsAdding User Management to Node.js
Adding User Management to Node.js
 
AI: Mobile Apps That Understands Your Intention When You Typed
AI: Mobile Apps That Understands Your Intention When You TypedAI: Mobile Apps That Understands Your Intention When You Typed
AI: Mobile Apps That Understands Your Intention When You Typed
 
Autodiscover flow in an office 365 environment part 3#3 part 31#36
Autodiscover flow in an office 365 environment  part 3#3  part 31#36Autodiscover flow in an office 365 environment  part 3#3  part 31#36
Autodiscover flow in an office 365 environment part 3#3 part 31#36
 
Security for oauth 2.0 - @topavankumarj
Security for oauth 2.0 - @topavankumarjSecurity for oauth 2.0 - @topavankumarj
Security for oauth 2.0 - @topavankumarj
 
OAuth 2.0
OAuth 2.0OAuth 2.0
OAuth 2.0
 
The State of OAuth2
The State of OAuth2The State of OAuth2
The State of OAuth2
 
GCM aperitivo Android
GCM aperitivo AndroidGCM aperitivo Android
GCM aperitivo Android
 
Securing your APIs with OAuth, OpenID, and OpenID Connect
Securing your APIs with OAuth, OpenID, and OpenID ConnectSecuring your APIs with OAuth, OpenID, and OpenID Connect
Securing your APIs with OAuth, OpenID, and OpenID Connect
 
Demystifying OAuth 2.0
Demystifying OAuth 2.0Demystifying OAuth 2.0
Demystifying OAuth 2.0
 

Ähnlich wie FOSS STHLM Android Cloud to Device Messaging

Android cloud to device messaging
Android cloud to device messagingAndroid cloud to device messaging
Android cloud to device messaging
Fe
 
Jasigsakai12 columbia-customizes-cas
Jasigsakai12 columbia-customizes-casJasigsakai12 columbia-customizes-cas
Jasigsakai12 columbia-customizes-cas
ellentuck
 
Colombo Mobile Developer MeetUp - Building Scalable Cloud Connected Mobile Ap...
Colombo Mobile Developer MeetUp - Building Scalable Cloud Connected Mobile Ap...Colombo Mobile Developer MeetUp - Building Scalable Cloud Connected Mobile Ap...
Colombo Mobile Developer MeetUp - Building Scalable Cloud Connected Mobile Ap...
99X Technology
 
Startup weekend bootcamp - Android up and running
Startup weekend bootcamp - Android up and runningStartup weekend bootcamp - Android up and running
Startup weekend bootcamp - Android up and running
Lance Nanek
 

Ähnlich wie FOSS STHLM Android Cloud to Device Messaging (20)

Android Cloud To Device Messaging
Android Cloud To Device MessagingAndroid Cloud To Device Messaging
Android Cloud To Device Messaging
 
Android cloud to device messaging
Android cloud to device messagingAndroid cloud to device messaging
Android cloud to device messaging
 
Workshop: Android
Workshop: AndroidWorkshop: Android
Workshop: Android
 
AC2DM For Security
AC2DM For SecurityAC2DM For Security
AC2DM For Security
 
Android chat in the cloud
Android chat in the cloudAndroid chat in the cloud
Android chat in the cloud
 
Jasigsakai12 columbia-customizes-cas
Jasigsakai12 columbia-customizes-casJasigsakai12 columbia-customizes-cas
Jasigsakai12 columbia-customizes-cas
 
1. device onboarding
1. device onboarding1. device onboarding
1. device onboarding
 
Android Froyo
Android FroyoAndroid Froyo
Android Froyo
 
Colombo Mobile Developer MeetUp - Building Scalable Cloud Connected Mobile Ap...
Colombo Mobile Developer MeetUp - Building Scalable Cloud Connected Mobile Ap...Colombo Mobile Developer MeetUp - Building Scalable Cloud Connected Mobile Ap...
Colombo Mobile Developer MeetUp - Building Scalable Cloud Connected Mobile Ap...
 
Build resource server &amp; client for OCF Cloud (2018.8.30)
Build resource server &amp; client for OCF Cloud (2018.8.30)Build resource server &amp; client for OCF Cloud (2018.8.30)
Build resource server &amp; client for OCF Cloud (2018.8.30)
 
testupload
testuploadtestupload
testupload
 
以Device Shadows與Rules Engine串聯實體世界
以Device Shadows與Rules Engine串聯實體世界以Device Shadows與Rules Engine串聯實體世界
以Device Shadows與Rules Engine串聯實體世界
 
Community call: Develop multi tenant apps with the Microsoft identity platform
Community call: Develop multi tenant apps with the Microsoft identity platformCommunity call: Develop multi tenant apps with the Microsoft identity platform
Community call: Develop multi tenant apps with the Microsoft identity platform
 
Push Notification in IBM MobileFirst Xamarin SDK
Push Notification in IBM MobileFirst Xamarin SDKPush Notification in IBM MobileFirst Xamarin SDK
Push Notification in IBM MobileFirst Xamarin SDK
 
Securing android applications
Securing android applicationsSecuring android applications
Securing android applications
 
Meteor Meet-up San Diego December 2014
Meteor Meet-up San Diego December 2014Meteor Meet-up San Diego December 2014
Meteor Meet-up San Diego December 2014
 
1. device onboarding pdf
1. device onboarding pdf1. device onboarding pdf
1. device onboarding pdf
 
Android C2DM Presentation at O'Reilly AndroidOpen Conference
Android C2DM Presentation at O'Reilly AndroidOpen ConferenceAndroid C2DM Presentation at O'Reilly AndroidOpen Conference
Android C2DM Presentation at O'Reilly AndroidOpen Conference
 
Startup weekend bootcamp - Android up and running
Startup weekend bootcamp - Android up and runningStartup weekend bootcamp - Android up and running
Startup weekend bootcamp - Android up and running
 
[WSO2Con EU 2017] Building Smart, Connected Products with WSO2 IoT Platform
[WSO2Con EU 2017] Building Smart, Connected Products with WSO2 IoT Platform[WSO2Con EU 2017] Building Smart, Connected Products with WSO2 IoT Platform
[WSO2Con EU 2017] Building Smart, Connected Products with WSO2 IoT Platform
 

Mehr von Johan Nilsson

Custom UI Components at Android Only 2011
Custom UI Components at Android Only 2011Custom UI Components at Android Only 2011
Custom UI Components at Android Only 2011
Johan Nilsson
 

Mehr von Johan Nilsson (10)

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

Kürzlich hochgeladen

Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 

Kürzlich hochgeladen (20)

ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptx
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 

FOSS STHLM Android Cloud to Device Messaging

  • 2.
  • 3.
  • 4.
  • 5. How to keep data fresh?
  • 6.
  • 7. Polling Simple to implement Ask for data periodically Radio draws a lot of power
  • 8.
  • 9. Pushing Harder to implement Less battery consumption Only uses network when needed Constant connection
  • 10. Components Intent Description of an action to perform BroadcastReceiver Recieve intents IntentService Handles asynchronous request, started when needed WakeLock Wake up the device at desired level AlarmManager Schedule the app to run in the future Synchronize polls with INTERVAL_*
  • 11. Some interesting projects CouchOne Mobile for Android http://www.couch.io/android Ericsson Labs - Mobile Push https://labs.ericsson.com/apis/mobile-push/ Whoopingkof - Evented Sockets http://github.com/voltron/whoopingkof/
  • 12.
  • 13. "It allows third-party application servers to send lightweight messages to their Android applications"
  • 14. "C2DM makes no guarantees about delivery or the order of messages"
  • 15. "An application on an Android device doesn’t need to be running to receive messages"
  • 16. "It does not provide any built-in user interface or other handling for message data"
  • 17. "It requires devices running Android 2.2 or higher that also have the Market application installed"
  • 18. "It uses an existing connection for Google services"
  • 20. Lifecycle Register device App server send message Device receives message Unregister device
  • 21.
  • 22. 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
  • 23. 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);
  • 24. 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. } }
  • 25. 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
  • 26. <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>
  • 27. <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>
  • 29. Send message 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. http://code.google.com/android/c2dm/index.html#lifecycle 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. From the documentation:
  • 30. Send message Retrieve ac2dm auth token (put on app server) Send authenticated POST - GoogleLogin auth=<TOKEN> - URL Encoded parameters registration_id collapse_key delay_while_idle - optional data.<KEY> - optional Using cURL to interact with Google Data services: http://code.google.com/apis/gdata/articles/using_cURL.html
  • 31. 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 ac2dm authorization token SID=DQAAA... LSID=DQAAA... Auth=DQAAA... Service name for C2DM Authorizatio n token
  • 32. 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); }
  • 33. 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>" Send message Response codes 200 OK - id=<MESSAGE ID> of sent message, success - Error=<ERROR CODE>, failed to send 401 Not Authorized 503 Service Unavailable, retry
  • 34. 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
  • 35. delay_while_idle Message is not immediately sent to the device if it is idle
  • 37. Receive a message 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 } } 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
  • 39. 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. } }
  • 40. Problems Can't send message to device if logged in with the role account 401