SlideShare uma empresa Scribd logo
1 de 39
Baixar para ler offline
A Journey into Google Cloud Messaging
“exploring the roots of crucial service for the Android eco-
system”
Simone Pulcini
simone.pulcini@gmail.com
it.linkedin.com/in/simonepulcini/
plus.google.com/+SimonePulcini
Main topics
● Overview with architectural tidbits
● Lifecycle
● Client setup and code
● 3rd party server with HTTP messages
About “Push communication”
● It’s a kind of Internet-based communication
between two parties
● It’s based on the publish-subscribe model
● Transaction is initiated by the publisher
(server)
● Clients subscribe a set of preferences in
advance
Push-based chat services
and so on…….
Components
● Client application: Android device with Android 2.2,
Google Play Store installed, logged Google account
● 3rd party Application Server: possibly a backend
component deployed on a server of your own that send
messages to Android devices using GCM
● GCM Connection Server: Google provided servers that
enables GCM
Credentials
1. Sender ID (obtained from API Console)
2. Application ID (declared on the android application
manifest.xml)
3. Registration ID (assigned by GCM servers to your
Android app)
4. Google account (needed for Android < 4.0.4)
5. Sender auth token (API key needed by 3rd party
application server to use GCM service)
GCM service architecture
Lifecycle (1 of 3): Enable GCM
● We have to declare our intent to use GCM on the
Android app, obtaining our registration id
● We need to do it just ONE TIME in our application life (i.
e we have to store our registration id on the device
using SharedPreferences)
String SENDER_ID = "My-Sender-ID";
GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(context);
String registrationId = gcm.register(SENDER_ID);
Lifecycle (2 of 3): msg send
● 3rd party server sends a message to GCM servers
● GCM servers enqueue and store it!
● As soon as each Android device is online, GCM
sends the msg to it
● On the device, Android OS broadcast msg to the
specified Android application using Intent broadcast
(only the right application receives the msg). Android
application could also be in a not running state
● Android app processes the msg
Lifecycle (3 of 3): msg receive
● Android receives the msg, then extract
key/value pairs from the payload
● Pairs are passed to the target app in a com.
google.android.c2dm.intent.RECEIVE Intent
● Target app extracts the values from Intent to
process them (it references them via keys)
Setup howto
This is what you need to start developing:
1. Google Play Services (http://developer.android.
com/google/play-services/setup.html)
2. Google API project from the cloud console (https:
//cloud.google.com/console) to obtain the project
number (your sender ID)
3. Turn on the GCM service
4. Obtain the API Key (needed for server side billing)
And now….
Your GCM Service is ready! It’s up to you to
code your Android client and your server
application (backend).
Let me show you how easy it is!
manifest.xml
Client: check Play Services
Call checkPlayServices() inside onCreate() and onResume()
Register GCM
checkAppVersion
registerInBackground
Receive a message
We need:
● a special mechanism to accept our RECEIVE intent, a
type of Broadcast Receiver. It receives the message
from the channel, passing it to…..
● ….an Intent Service that parses the message and calls
our logic (what we want do with this message)
Wakeful Broadcast Receiver
Intent Service (1 of 2)
Intent Service (2 of 2)
Some defs for you about msgs
Send to sync message: a message sent by
server to tell the client that there’s something
new server side
Payload message: a message sent by server
to the client that contains some data for the
client (a “payload”)
And now...let’s go server side!
It’s important to remember that you can
connect to GCM using two protocols:
● HTTP
● XMPP
In this talk we’ll cover HTTP only connections
(you can find lots of documentation on the
internet on how to use XMPP with GCM)
HTTP Server vs Cloud Connection Server
1. Cloud to device only
2. Uses HTTP POST and a
synchronous
mechanism (wait until
received)
3. JSON msg on HTTP
POST
1. Cloud to device and
device to cloud
2. Uses an XMPP
persistent asynchronous
connection with ACK e
NACK encapsulated in
JSON
3. JSON msg on XMPP
HTTP CCS
What you need to implement
In our 3rd party server we need to:
1. Send a msg to GCM server
2. Expose an interface to our client (Android) to
communicate with it
3. Store API key and registration IDs
4. Generate unique message IDs for each msg
sent
Message parameters
Time to go deep into a GCM message format.
We’ll look at required [R] and optional [O]
message parameters.
Remember we’ll discuss HTTP message
parameters only!
Here you are...parameters!
● registration_ids [R]: string array of devices. range: 1 to 1000
● notification_key [O]: maps an user to a set of registration_ids. Msg will be sent to the whole group of
registration_ids covered by notification_key. Example: owner of multiple android devices (phone, tablet etc) with
the same app installed on each of them.
● collapse_key [O]: an arbitrary string to mark n message. If the device is offline, and n message have been
stored by GCM with the same collapse key, only the last one will be sent to the device as soon as it will be online
again. No guarantee on the fact that the last message pushed by 3rd party server on GCM will be the one sent.
range: 1 to 4
● data [O]: optional payload of 4kb maximus stored as a JSON object. Keys are restricted to avoid using some
reserved words. Values can be also json object but GCM will convert them to strings.
● delay_while_idle [O]: a json boolean. If true, msg will be sent when the device wakes up from idle. If
collapse_key was defined, last message enqueued with that key will be sent
● time_to_live [O]: time in seconds. Time for GCM to store a message if device is in idle or offline state. Default is
4 weeks
● restricted_package_name[O]: package name of your app. Msg will be sent to registration_ids that match this
package name
● dry_run [O]: json boolean. If true no msg will be sent. Just a test for your 3rd party server during some debug!
Http header for JSON msg
Two headers for the GCM needed!
● Authorization: key = your_api_key
● Content-type: application/json
Message example 1
Message example 2
Message example 3
HTTP Response codes
● 200: Yes!!! Done. See the response
message to have more details
● 400: Problem parsing a JSON request. See
the response message for more details
● 401: Authentication problem
● 5xx: GCM service issue. Want to retry? See
the suggested time provided in the response
message
JSON Response fields
● multicast_id : unique id identifying a multicast message
● success: number of message sent
● failure: number of message failed to be sent
● canonical_ids: number of results that contain a canonical registration_id
● results: array of objects with the status of each message processed by
GCM, listed in request order. It contains these fields:
○ message_id: id of the message processed succefully
○ error: a string with an error message
○ registration_id: this message was processed but next time the client
should use the registration_id specified, not the previous one. This
field is not set in case of an error.
Error messages
● Missing registration ID: you forget to insert a registration ID in your request
● Invalid registration ID: it does not match the registration ID on the device (check length for example)
● Mismatched sender: You’re not a valid sender for this registration ID (the client hasn’t declared you as a valid
sender)
● Unregistered device: device is unregistered (for example: application has been uninstalled or registration id is
expired due to Google decision to renew it
● Message too big: do you remember that the payload max size is 4096 bytes?
● Invalid data key: your key value in the JSON payload is a reserved word for GCM
● Invalid time to live: your TTL is not in the range from 0 to 2419200 (4 weeks)
● Authentication error: double check your auth credentials (i.e the authorization header of your message)
● Timeout: GCM server timeout. Resend your message but respect conditions reported in the error (as Retry-After
as well as an exponential back-off in your retry mechanism)
● Internal server error: something gone wrong in GCM server. Maybe you should wait a litte or try to ask for
some support in Google support forum
● Invalid package name: You passed a package name for a registration id in your request that does not match
the client package name
Response example 1
Response example 2
References
● http://developer.android.
com/google/gcm/index.html
● https://code.google.com/p/gcm/
● https://github.
com/spulci/gdg_rome/tree/master/GdgRome
IOTDemoModel

Mais conteúdo relacionado

Semelhante a A Journey into Google Cloud Messaging

google cloud messaging
google cloud messaginggoogle cloud messaging
google cloud messagingBhavana Sharma
 
Google Cloud Messaging
Google Cloud Messaging Google Cloud Messaging
Google Cloud Messaging Lavakush Verma
 
GCM Android
GCM AndroidGCM Android
GCM Androidaswapnal
 
Introduction to google cloud messaging in android
Introduction to google cloud messaging in androidIntroduction to google cloud messaging in android
Introduction to google cloud messaging in androidRIA RUI Society
 
GCM with Pushbots
GCM with PushbotsGCM with Pushbots
GCM with PushbotsAshish RAj
 
Building your First gRPC Service
Building your First gRPC ServiceBuilding your First gRPC Service
Building your First gRPC ServiceJessie Barnett
 
Push Notification for Android, iOS & Sever Side Using Firebase Cloud Messaging
Push Notification for Android, iOS & Sever Side Using Firebase Cloud MessagingPush Notification for Android, iOS & Sever Side Using Firebase Cloud Messaging
Push Notification for Android, iOS & Sever Side Using Firebase Cloud MessagingCumulations Technologies
 
How to connect 1980 and 2018
How to connect 1980 and 2018How to connect 1980 and 2018
How to connect 1980 and 2018Matthieu Kern
 
Максим Щеглов - Google Cloud Messaging for Android
Максим Щеглов - Google Cloud Messaging for AndroidМаксим Щеглов - Google Cloud Messaging for Android
Максим Щеглов - Google Cloud Messaging for AndroidUA Mobile
 
Google Cloud Messaging
Google Cloud Messaging Google Cloud Messaging
Google Cloud Messaging Sandip Jadhav
 
我的GCM時代-推送訊息的實做分享
我的GCM時代-推送訊息的實做分享我的GCM時代-推送訊息的實做分享
我的GCM時代-推送訊息的實做分享Morning Kao
 
GOOGLE CLOUD MESSAGING (GCM): A LIGHT WEIGHT COMMUNICATION MECHANISM BETWEEN ...
GOOGLE CLOUD MESSAGING (GCM): A LIGHT WEIGHT COMMUNICATION MECHANISM BETWEEN ...GOOGLE CLOUD MESSAGING (GCM): A LIGHT WEIGHT COMMUNICATION MECHANISM BETWEEN ...
GOOGLE CLOUD MESSAGING (GCM): A LIGHT WEIGHT COMMUNICATION MECHANISM BETWEEN ...ijistjournal
 
GOOGLE CLOUD MESSAGING PPT 2017
GOOGLE CLOUD MESSAGING PPT 2017GOOGLE CLOUD MESSAGING PPT 2017
GOOGLE CLOUD MESSAGING PPT 2017ketan Bordekar
 
Chat app case study - xmpp vs SIP
Chat app case study - xmpp vs SIPChat app case study - xmpp vs SIP
Chat app case study - xmpp vs SIPGenora Infotech
 

Semelhante a A Journey into Google Cloud Messaging (20)

google cloud messaging
google cloud messaginggoogle cloud messaging
google cloud messaging
 
google cloud messaging
google cloud messaginggoogle cloud messaging
google cloud messaging
 
Google Cloud Messaging
Google Cloud Messaging Google Cloud Messaging
Google Cloud Messaging
 
GCM aperitivo Android
GCM aperitivo AndroidGCM aperitivo Android
GCM aperitivo Android
 
GCM Android
GCM AndroidGCM Android
GCM Android
 
Gcm tutorial
Gcm tutorialGcm tutorial
Gcm tutorial
 
Introduction to google cloud messaging in android
Introduction to google cloud messaging in androidIntroduction to google cloud messaging in android
Introduction to google cloud messaging in android
 
GCM with Pushbots
GCM with PushbotsGCM with Pushbots
GCM with Pushbots
 
Magda badita gcm
Magda badita  gcmMagda badita  gcm
Magda badita gcm
 
Building your First gRPC Service
Building your First gRPC ServiceBuilding your First gRPC Service
Building your First gRPC Service
 
Push Notification for Android, iOS & Sever Side Using Firebase Cloud Messaging
Push Notification for Android, iOS & Sever Side Using Firebase Cloud MessagingPush Notification for Android, iOS & Sever Side Using Firebase Cloud Messaging
Push Notification for Android, iOS & Sever Side Using Firebase Cloud Messaging
 
How to connect 1980 and 2018
How to connect 1980 and 2018How to connect 1980 and 2018
How to connect 1980 and 2018
 
Максим Щеглов - Google Cloud Messaging for Android
Максим Щеглов - Google Cloud Messaging for AndroidМаксим Щеглов - Google Cloud Messaging for Android
Максим Щеглов - Google Cloud Messaging for Android
 
Google Cloud Messaging
Google Cloud Messaging Google Cloud Messaging
Google Cloud Messaging
 
我的GCM時代-推送訊息的實做分享
我的GCM時代-推送訊息的實做分享我的GCM時代-推送訊息的實做分享
我的GCM時代-推送訊息的實做分享
 
GOOGLE CLOUD MESSAGING (GCM): A LIGHT WEIGHT COMMUNICATION MECHANISM BETWEEN ...
GOOGLE CLOUD MESSAGING (GCM): A LIGHT WEIGHT COMMUNICATION MECHANISM BETWEEN ...GOOGLE CLOUD MESSAGING (GCM): A LIGHT WEIGHT COMMUNICATION MECHANISM BETWEEN ...
GOOGLE CLOUD MESSAGING (GCM): A LIGHT WEIGHT COMMUNICATION MECHANISM BETWEEN ...
 
GOOGLE CLOUD MESSAGING PPT 2017
GOOGLE CLOUD MESSAGING PPT 2017GOOGLE CLOUD MESSAGING PPT 2017
GOOGLE CLOUD MESSAGING PPT 2017
 
Chat app case study - xmpp vs SIP
Chat app case study - xmpp vs SIPChat app case study - xmpp vs SIP
Chat app case study - xmpp vs SIP
 
Messaging APIs of RingCentral
Messaging APIs of RingCentralMessaging APIs of RingCentral
Messaging APIs of RingCentral
 
Google Cloud Messaging
Google Cloud Messaging Google Cloud Messaging
Google Cloud Messaging
 

Último

AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesVictorSzoltysek
 
Exploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfExploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfproinshot.com
 
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdfAzure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdfryanfarris8
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️Delhi Call girls
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplatePresentation.STUDIO
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️Delhi Call girls
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnAmarnathKambale
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...panagenda
 
10 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 202410 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 2024Mind IT Systems
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerThousandEyes
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...OnePlan Solutions
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 

Último (20)

AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
 
Exploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfExploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdf
 
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdfAzure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
10 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 202410 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 2024
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 

A Journey into Google Cloud Messaging

  • 1.
  • 2. A Journey into Google Cloud Messaging “exploring the roots of crucial service for the Android eco- system”
  • 4. Main topics ● Overview with architectural tidbits ● Lifecycle ● Client setup and code ● 3rd party server with HTTP messages
  • 5. About “Push communication” ● It’s a kind of Internet-based communication between two parties ● It’s based on the publish-subscribe model ● Transaction is initiated by the publisher (server) ● Clients subscribe a set of preferences in advance
  • 7. Components ● Client application: Android device with Android 2.2, Google Play Store installed, logged Google account ● 3rd party Application Server: possibly a backend component deployed on a server of your own that send messages to Android devices using GCM ● GCM Connection Server: Google provided servers that enables GCM
  • 8. Credentials 1. Sender ID (obtained from API Console) 2. Application ID (declared on the android application manifest.xml) 3. Registration ID (assigned by GCM servers to your Android app) 4. Google account (needed for Android < 4.0.4) 5. Sender auth token (API key needed by 3rd party application server to use GCM service)
  • 10. Lifecycle (1 of 3): Enable GCM ● We have to declare our intent to use GCM on the Android app, obtaining our registration id ● We need to do it just ONE TIME in our application life (i. e we have to store our registration id on the device using SharedPreferences) String SENDER_ID = "My-Sender-ID"; GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(context); String registrationId = gcm.register(SENDER_ID);
  • 11. Lifecycle (2 of 3): msg send ● 3rd party server sends a message to GCM servers ● GCM servers enqueue and store it! ● As soon as each Android device is online, GCM sends the msg to it ● On the device, Android OS broadcast msg to the specified Android application using Intent broadcast (only the right application receives the msg). Android application could also be in a not running state ● Android app processes the msg
  • 12. Lifecycle (3 of 3): msg receive ● Android receives the msg, then extract key/value pairs from the payload ● Pairs are passed to the target app in a com. google.android.c2dm.intent.RECEIVE Intent ● Target app extracts the values from Intent to process them (it references them via keys)
  • 13. Setup howto This is what you need to start developing: 1. Google Play Services (http://developer.android. com/google/play-services/setup.html) 2. Google API project from the cloud console (https: //cloud.google.com/console) to obtain the project number (your sender ID) 3. Turn on the GCM service 4. Obtain the API Key (needed for server side billing)
  • 14. And now…. Your GCM Service is ready! It’s up to you to code your Android client and your server application (backend). Let me show you how easy it is!
  • 16. Client: check Play Services Call checkPlayServices() inside onCreate() and onResume()
  • 20. Receive a message We need: ● a special mechanism to accept our RECEIVE intent, a type of Broadcast Receiver. It receives the message from the channel, passing it to….. ● ….an Intent Service that parses the message and calls our logic (what we want do with this message)
  • 24. Some defs for you about msgs Send to sync message: a message sent by server to tell the client that there’s something new server side Payload message: a message sent by server to the client that contains some data for the client (a “payload”)
  • 25. And now...let’s go server side! It’s important to remember that you can connect to GCM using two protocols: ● HTTP ● XMPP In this talk we’ll cover HTTP only connections (you can find lots of documentation on the internet on how to use XMPP with GCM)
  • 26. HTTP Server vs Cloud Connection Server 1. Cloud to device only 2. Uses HTTP POST and a synchronous mechanism (wait until received) 3. JSON msg on HTTP POST 1. Cloud to device and device to cloud 2. Uses an XMPP persistent asynchronous connection with ACK e NACK encapsulated in JSON 3. JSON msg on XMPP HTTP CCS
  • 27. What you need to implement In our 3rd party server we need to: 1. Send a msg to GCM server 2. Expose an interface to our client (Android) to communicate with it 3. Store API key and registration IDs 4. Generate unique message IDs for each msg sent
  • 28. Message parameters Time to go deep into a GCM message format. We’ll look at required [R] and optional [O] message parameters. Remember we’ll discuss HTTP message parameters only!
  • 29. Here you are...parameters! ● registration_ids [R]: string array of devices. range: 1 to 1000 ● notification_key [O]: maps an user to a set of registration_ids. Msg will be sent to the whole group of registration_ids covered by notification_key. Example: owner of multiple android devices (phone, tablet etc) with the same app installed on each of them. ● collapse_key [O]: an arbitrary string to mark n message. If the device is offline, and n message have been stored by GCM with the same collapse key, only the last one will be sent to the device as soon as it will be online again. No guarantee on the fact that the last message pushed by 3rd party server on GCM will be the one sent. range: 1 to 4 ● data [O]: optional payload of 4kb maximus stored as a JSON object. Keys are restricted to avoid using some reserved words. Values can be also json object but GCM will convert them to strings. ● delay_while_idle [O]: a json boolean. If true, msg will be sent when the device wakes up from idle. If collapse_key was defined, last message enqueued with that key will be sent ● time_to_live [O]: time in seconds. Time for GCM to store a message if device is in idle or offline state. Default is 4 weeks ● restricted_package_name[O]: package name of your app. Msg will be sent to registration_ids that match this package name ● dry_run [O]: json boolean. If true no msg will be sent. Just a test for your 3rd party server during some debug!
  • 30. Http header for JSON msg Two headers for the GCM needed! ● Authorization: key = your_api_key ● Content-type: application/json
  • 34. HTTP Response codes ● 200: Yes!!! Done. See the response message to have more details ● 400: Problem parsing a JSON request. See the response message for more details ● 401: Authentication problem ● 5xx: GCM service issue. Want to retry? See the suggested time provided in the response message
  • 35. JSON Response fields ● multicast_id : unique id identifying a multicast message ● success: number of message sent ● failure: number of message failed to be sent ● canonical_ids: number of results that contain a canonical registration_id ● results: array of objects with the status of each message processed by GCM, listed in request order. It contains these fields: ○ message_id: id of the message processed succefully ○ error: a string with an error message ○ registration_id: this message was processed but next time the client should use the registration_id specified, not the previous one. This field is not set in case of an error.
  • 36. Error messages ● Missing registration ID: you forget to insert a registration ID in your request ● Invalid registration ID: it does not match the registration ID on the device (check length for example) ● Mismatched sender: You’re not a valid sender for this registration ID (the client hasn’t declared you as a valid sender) ● Unregistered device: device is unregistered (for example: application has been uninstalled or registration id is expired due to Google decision to renew it ● Message too big: do you remember that the payload max size is 4096 bytes? ● Invalid data key: your key value in the JSON payload is a reserved word for GCM ● Invalid time to live: your TTL is not in the range from 0 to 2419200 (4 weeks) ● Authentication error: double check your auth credentials (i.e the authorization header of your message) ● Timeout: GCM server timeout. Resend your message but respect conditions reported in the error (as Retry-After as well as an exponential back-off in your retry mechanism) ● Internal server error: something gone wrong in GCM server. Maybe you should wait a litte or try to ask for some support in Google support forum ● Invalid package name: You passed a package name for a registration id in your request that does not match the client package name
  • 39. References ● http://developer.android. com/google/gcm/index.html ● https://code.google.com/p/gcm/ ● https://github. com/spulci/gdg_rome/tree/master/GdgRome IOTDemoModel