SlideShare a Scribd company logo
Android chat in the cloud
Android chat in the cloud
RESTful APIs, authentication, push notifications and some additional goodies
Alfredo Morresi
Developer Relations @ Google
Who I am
Alfredo Morresi

ROLE
Developer Relations Program Manager
COUNTRY
Italy
PASSIONS
Community, Development,
Snowboarding, Tiramisu'
REACH ME
alfredomorresi@google.com
plus.google.com/+AlfredoMorresi
@rainbowbreeze
Let’s start with the chat demo app

Download from https://play.google.com/store/apps/details?id=org.alexismp.cloud.backend
In less than 40 minutes?
Forget about the backend!
Use Google Cloud Platform + Mobile Backend Starter
Optional server-side coding: Control your cloud service using Android and iOS client libraries.
Cloud Datastore: Store millions of objects in the cloud and manage them from your app.
Push Notifications: Send and broadcast objects as messages via Apple Push Notifications and
Google Cloud Messaging.
Event Driven Programming: Create real-time interactive user experiences using Continuous
Queries.
User authentication: Authenticate users using Google Accounts and control access on private data.
Built to scale: Mobile backend runs on App Engine infrastructure to scale to millions of users within
hours.
Create your backend

https://developers.google.com/cloud/samples/mbs
Create your backend
Create your backend
Create your backend
Download Android app source code

http://goo.gl/0FLRPp
Set some values in the source and you’ve done!

Change
●
●
●

PROJECT_ID
PROJECT_NUMBER
WEB_CLIENT_ID
Android chat in the cloud
Step 1
Accessing to the APIs
Google Cloud Endpoints: generate APIs from annotations

https://developers.google.com/appengine/docs/java/endpoints/
Explore the backend APIs
Explore the APIs:
http://<YOUR_PROJECT_ID>.appspot.com/_ah/api/explorer
Set Open authentication in the backend
Access to RESTful APIs, no authentication
Set the Consts.IS_AUTH_ENABLED to false
Set the Consts.PROJECT_ID to
It was easy!
Access to RESTful APIs, no authentication
Google Cloud Endpoints automatically generates the
Android code required to access the backend APIs
Mobilebackend.Builder builder = new Mobilebackend.Builder(
AndroidHttp.newCompatibleTransport(),
new GsonFactory(),
null);
Mobilebackend backend =
builder.setRootUrl(Consts.ENDPOINT_ROOT_URL).build();
Access to RESTful APIs, no authentication
Insert a new CloudEntity in the backend
CloudEntity post = new CloudEntity("Guestbook");
post.put("message", "Your message here...");
EntityDto resultEntityDto = backend.endpointV1()
.insert(post.getKindName(), post.getEntityDto()).execute();
CloudEntity resultCo =
CloudEntity.createCloudEntityFromEntityDto
(resultEntityDto);
Log.i(Consts.TAG, "insert: inserted: " + resultCo);
Step 2
Accessing to the APIs with authentication
Authenticated access to the APIs
Restrict the API access only to your application(s).
ANDROID Client_ID: identifies your app in unique
way (package name + SHA1 of signing key of the app)
WEB Client_ID: establishes that the client and the
server are from the same developer so the standard
OAuth2 prompt is avoided (no 3rd party app). It’s a
shared token.
https://developers.google.com/appengine/docs/java/endpoints/auth
Generate Android Client ID
Generate Android Client ID
Generate Web Client ID
Generate Web Client ID
Set Android and Web Client IDs in the backend
Authenticated access to the APIs

Set the Consts.IS_AUTH_ENABLED to true
Set the Consts.WEB_CLIENT_ID to Web Client ID
Android chat in the cloud
The Android client provides credentials!
GoogleAccountCredential credential =
GoogleAccountCredential.usingAudience(
getActivity(), Consts.AUTH_AUDIENCE);
if (credential.getSelectedAccountName() == null) {
startActivityForResult(
credential.newChooseAccountIntent(),
REQUEST_ACCOUNT_PICKER);
String accountName =
data.getStringExtra(AccountManager.KEY_ACCOUNT_NAME);
credential.setSelectedAccountName(accountName);
https://developers.google.
com/appengine/docs/java/endpoints/consume_android#Java_Making_aut
henticated_calls
Authenticated access to the APIs
Inject the credential in the backend manager class
// check if credential has account name
final GoogleAccountCredential gac =
credential == null || credential.getSelectedAccountName() == null
? null
: mCredential;
// create HttpRequestInitializer
HttpRequestInitializer httpRequestInitializer = new HttpRequestInitializer() {
@Override
public void initialize(HttpRequest request) throws IOException {
if (gac != null) {
gac.initialize(request);
}
}
};
Authenticated access to the APIs
Mobilebackend.Builder builder = new Mobilebackend.Builder(
AndroidHttp.newCompatibleTransport(),
new GsonFactory(),
httpRequestInitializer);
Mobilebackend backend =
builder.setRootUrl(Consts.ENDPOINT_ROOT_URL).build();
… Now

the API backend framework automatically
authenticates the user and enforces the authorized
clientIds whitelist, ultimately by supplying a valid
User to the API parameters.
Step 3
Add push notifications
Android chat in the cloud
Google Cloud Messaging for Android

http://developer.android.com/google/gcm/index.html
Enable GCM in the project
Generate a Server API Key
Generate a Server API Key
Enable GCM in the backend
Enable GCM in the client

Set the Consts.PROJECT_NUMBER to
Android chat in the cloud
A look into GCM client code
http://developer.android.com/google/gcm/client.html

Register your app and store registration ID
String regId = getRegIdFromPref();
if (registrationId.isEmpty()) {
regid = GoogleCloudMessaging.getInstance(context)
.register(PROJECT_ID);
storeRegIdToPref(regId);
}
Create a BroadcastReceiver to receive push messages
@Override
public void onReceive(Context context, Intent intent) {
// Explicitly specify that GcmIntentService will handle the intent
ComponentName comp =
new ComponentName(
context.getPackageName(),
GCMIntentService.class.getName());
// Start service, keeping the device awake while it is launching
startWakefulService(context, (intent.setComponent(comp)));
setResultCode(Activity.RESULT_OK);
}
Handle the message with a Service
protected void onHandleIntent(Intent intent) {
Bundle extras = intent.getExtras();
GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
String msgType = gcm.getMessageType(intent);
if (extras.isEmpty()) { // has effect of unparcelling Bundle
…
}
if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE.equals(messageType)) {
…
}
// Release the wake lock provided by the WakefulBroadcastReceiver.
GCMBroadcastReceiver.completeWakefulIntent(intent);
}
And remember to...

App registration is a network operation
Bonus Step
App internal architecture
Because API calls are slow...

EntityDto resultEntityDto = backend.endpointV1()
.insert(post.getKindName(), post.getEntityDto()).execute();
Never forget!
CloudBackendASync extends CloudBackend
// create a response handler that will receive the result or an error
CloudCallbackHandler<List<CloudEntity>> handler =
new CloudCallbackHandler<List<CloudEntity>>() {
@Override
public void onComplete(List<CloudEntity> results) {
...
}
@Override
public void onError(IOException exception) {
...
}
CloudBackendASync extends CloudBackend

// execute the query with the handler
mProcessingFragment.getCloudBackend().listByKind(
"Guestbook",
CloudEntity.PROP_CREATED_AT,
Order.DESC,
50,
Scope.FUTURE_AND_PAST, handler);
Why these two classes?

Separate the logic
(CloudBackend) from the sync
management
(CloudBackendAsync) makes
the code more testable!
Activity lifecycle (you can do better!)
// Check to see if we have retained the fragment which handles asynchronous backend calls
mProcessingFragment = (CloudBackendFragment) mFragmentManager.
findFragmentByTag(PROCESSING_FRAGMENT_TAG);
// If not retained (or first time running), create a new one
if (mProcessingFragment == null) {
mProcessingFragment = new CloudBackendFragment();
mProcessingFragment.setRetainInstance(true);
fragmentTransaction.add(mProcessingFragment, PROCESSING_FRAGMENT_TAG);
}
…
// execute the insertion with the handler
mProcessingFragment.getCloudBackend().insert(newPost, handler);
mMessageTxt.setEnabled(false);
mSendBtn.setEnabled(false);
Extends the data

CloudEntity post = new CloudEntity("Guestbook");
post.put("message", "Your message here...");
post.put("alf_property", "Custom property value here...");
EntityDto resultEntityDto = backend.endpointV1()
.insert(post.getKindName(), post.getEntityDto()).execute();
CloudEntity resultCo =
CloudEntity.createCloudEntityFromEntityDto(resultEntityDto);
Curious about Google dev initiatives and event in Italy?

https://developersitalia.blogspot.com
Thank you!
http://developers.google.com
Alfredo Morresi
plus.google.com/+AlfredoMorresi
@rainbowbreeze

More Related Content

PPT
Intro to Android Programming
PPTX
Week 1 - Android Study Jams
PDF
End-to-end Mobile App Development (with iOS and Azure Mobile Services)
PDF
Android Development: Build Android App from Scratch
PDF
Android 6.0 Marshmallow - Everything you need to know !
PPTX
Gdsc android introduction
PPTX
Android Programming made easy
PPT
Industrial Training in Android Application
Intro to Android Programming
Week 1 - Android Study Jams
End-to-end Mobile App Development (with iOS and Azure Mobile Services)
Android Development: Build Android App from Scratch
Android 6.0 Marshmallow - Everything you need to know !
Gdsc android introduction
Android Programming made easy
Industrial Training in Android Application

What's hot (20)

PDF
Intel ndk - a few Benchmarks
PDF
Intro to Windows Azure Mobile Services with iOS
PPTX
Android Development Training
PDF
Wearables + Azure development
ODP
Architecture your android_application
PPTX
Introduction to Android programming
ODP
Introduction to Android App Development
PPTX
Android Workshop Day 1 Part 2
PPTX
Project presentation (Loginradius SDK for Android)
PPTX
Introduction to Android Development: Before Getting Started
PDF
FYPJ - Cerebral Android App Development (Report)
DOCX
Questions About Android Application Development
PPT
android-tutorial-for-beginner
PPTX
Appcelerator Titanium - An Introduction to the Titanium Ecosystem
PPTX
Android Studio Overview
PPT
Android application structure
ODP
Ci for Android
PDF
Using Maven to build Java & Android program
PPT
Mobile Application Development With Android
PDF
Android Workshop Part 1
Intel ndk - a few Benchmarks
Intro to Windows Azure Mobile Services with iOS
Android Development Training
Wearables + Azure development
Architecture your android_application
Introduction to Android programming
Introduction to Android App Development
Android Workshop Day 1 Part 2
Project presentation (Loginradius SDK for Android)
Introduction to Android Development: Before Getting Started
FYPJ - Cerebral Android App Development (Report)
Questions About Android Application Development
android-tutorial-for-beginner
Appcelerator Titanium - An Introduction to the Titanium Ecosystem
Android Studio Overview
Android application structure
Ci for Android
Using Maven to build Java & Android program
Mobile Application Development With Android
Android Workshop Part 1
Ad

Viewers also liked (7)

PDF
Apertura "Mobile & Embedded" - 13 febbraio 2014
PPT
#Html2Native
PDF
Clean android code
PDF
EE Incremental Store
PDF
Programming objects with android
PDF
IoT, serve?
PDF
Introduction to Google Project Tango and Intel® RealSense™
Apertura "Mobile & Embedded" - 13 febbraio 2014
#Html2Native
Clean android code
EE Incremental Store
Programming objects with android
IoT, serve?
Introduction to Google Project Tango and Intel® RealSense™
Ad

Similar to Android chat in the cloud (20)

PDF
appengine ja night #24 Google Cloud Endpoints and BigQuery (English)
PDF
Google Cloud Endpoints: Building Third-Party APIs on Google AppEngine
PDF
Build Android App using GCE & GAE
PDF
Google App Engine
PDF
Google app-engine-cloudcamplagos2011
PPTX
Gcm presentation
PDF
Android Cloud to Device Messaging Framework at GTUG Stockholm
PDF
Google Cloud Messaging
PDF
#MBLTdev: Разработка backend для мобильного приложения с использованием Googl...
PDF
300 - Multiplatform Apps on Google Cloud Platform
PPTX
Google Cloud Platform
PDF
Mobile backends with Google Cloud Platform (MBLTDev'14)
PPT
Oracle mcs overview 1029
PDF
A Journey into Google Cloud Messaging
PDF
FOSS STHLM Android Cloud to Device Messaging
PPTX
Android Cloud to Device Messaging with the Google App Engine
PDF
Modern Web Cloud Architecture based on Google Technologies
PDF
Google cloud messaging
PDF
Mobile game architecture on GCP
PPTX
Introduction to google endpoints
appengine ja night #24 Google Cloud Endpoints and BigQuery (English)
Google Cloud Endpoints: Building Third-Party APIs on Google AppEngine
Build Android App using GCE & GAE
Google App Engine
Google app-engine-cloudcamplagos2011
Gcm presentation
Android Cloud to Device Messaging Framework at GTUG Stockholm
Google Cloud Messaging
#MBLTdev: Разработка backend для мобильного приложения с использованием Googl...
300 - Multiplatform Apps on Google Cloud Platform
Google Cloud Platform
Mobile backends with Google Cloud Platform (MBLTDev'14)
Oracle mcs overview 1029
A Journey into Google Cloud Messaging
FOSS STHLM Android Cloud to Device Messaging
Android Cloud to Device Messaging with the Google App Engine
Modern Web Cloud Architecture based on Google Technologies
Google cloud messaging
Mobile game architecture on GCP
Introduction to google endpoints

More from firenze-gtug (20)

PDF
Html5 apps - GWT oriented
PDF
Android ndk - ottimizzazione su dispositivi Intel
PDF
Gwt kickoff - Alberto Mancini & Francesca Tosi
PDF
Youtube broadcast live - Massimiliano D'Ambrosio
PDF
Intro BeagleBone Black - Massimiliano D'Ambrosio
PDF
Arduino - Massimiliano D'Ambrosio
PDF
Introduzione a GAE - Alessandro Aglietti e Lorenzo Bugiani
PDF
RFID: What & Why - Stefano Coluccini
PDF
GWT - AppDays - (25 aprile 2014, pordenone)
PDF
Presentazione Google App Engine
PDF
Maven from dummies
PPTX
Apps fuel oct2012
PDF
Dev fest android application case study
PDF
google drive and the google drive sdk
PDF
You tube api overview
PDF
AdWordsScripts v1
PDF
Gwt development with errai and forge
PDF
Google tv gdg_devfest_firenze2012
PDF
Dev fest2012 opening
PDF
Unconventional webapps with gwt:elemental & html5
Html5 apps - GWT oriented
Android ndk - ottimizzazione su dispositivi Intel
Gwt kickoff - Alberto Mancini & Francesca Tosi
Youtube broadcast live - Massimiliano D'Ambrosio
Intro BeagleBone Black - Massimiliano D'Ambrosio
Arduino - Massimiliano D'Ambrosio
Introduzione a GAE - Alessandro Aglietti e Lorenzo Bugiani
RFID: What & Why - Stefano Coluccini
GWT - AppDays - (25 aprile 2014, pordenone)
Presentazione Google App Engine
Maven from dummies
Apps fuel oct2012
Dev fest android application case study
google drive and the google drive sdk
You tube api overview
AdWordsScripts v1
Gwt development with errai and forge
Google tv gdg_devfest_firenze2012
Dev fest2012 opening
Unconventional webapps with gwt:elemental & html5

Recently uploaded (20)

PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PDF
Encapsulation theory and applications.pdf
PDF
cuic standard and advanced reporting.pdf
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PDF
Encapsulation_ Review paper, used for researhc scholars
PDF
Machine learning based COVID-19 study performance prediction
PPTX
Understanding_Digital_Forensics_Presentation.pptx
PPTX
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PDF
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PPTX
sap open course for s4hana steps from ECC to s4
PPTX
Programs and apps: productivity, graphics, security and other tools
PDF
Review of recent advances in non-invasive hemoglobin estimation
PDF
Empathic Computing: Creating Shared Understanding
PPTX
Big Data Technologies - Introduction.pptx
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
20250228 LYD VKU AI Blended-Learning.pptx
Reach Out and Touch Someone: Haptics and Empathic Computing
Encapsulation theory and applications.pdf
cuic standard and advanced reporting.pdf
Per capita expenditure prediction using model stacking based on satellite ima...
Encapsulation_ Review paper, used for researhc scholars
Machine learning based COVID-19 study performance prediction
Understanding_Digital_Forensics_Presentation.pptx
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
Dropbox Q2 2025 Financial Results & Investor Presentation
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
Agricultural_Statistics_at_a_Glance_2022_0.pdf
The Rise and Fall of 3GPP – Time for a Sabbatical?
sap open course for s4hana steps from ECC to s4
Programs and apps: productivity, graphics, security and other tools
Review of recent advances in non-invasive hemoglobin estimation
Empathic Computing: Creating Shared Understanding
Big Data Technologies - Introduction.pptx
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...

Android chat in the cloud

  • 2. Android chat in the cloud RESTful APIs, authentication, push notifications and some additional goodies Alfredo Morresi Developer Relations @ Google
  • 3. Who I am Alfredo Morresi ROLE Developer Relations Program Manager COUNTRY Italy PASSIONS Community, Development, Snowboarding, Tiramisu' REACH ME alfredomorresi@google.com plus.google.com/+AlfredoMorresi @rainbowbreeze
  • 4. Let’s start with the chat demo app Download from https://play.google.com/store/apps/details?id=org.alexismp.cloud.backend
  • 5. In less than 40 minutes?
  • 6. Forget about the backend!
  • 7. Use Google Cloud Platform + Mobile Backend Starter Optional server-side coding: Control your cloud service using Android and iOS client libraries. Cloud Datastore: Store millions of objects in the cloud and manage them from your app. Push Notifications: Send and broadcast objects as messages via Apple Push Notifications and Google Cloud Messaging. Event Driven Programming: Create real-time interactive user experiences using Continuous Queries. User authentication: Authenticate users using Google Accounts and control access on private data. Built to scale: Mobile backend runs on App Engine infrastructure to scale to millions of users within hours.
  • 12. Download Android app source code http://goo.gl/0FLRPp
  • 13. Set some values in the source and you’ve done! Change ● ● ● PROJECT_ID PROJECT_NUMBER WEB_CLIENT_ID
  • 16. Google Cloud Endpoints: generate APIs from annotations https://developers.google.com/appengine/docs/java/endpoints/
  • 17. Explore the backend APIs Explore the APIs: http://<YOUR_PROJECT_ID>.appspot.com/_ah/api/explorer
  • 18. Set Open authentication in the backend
  • 19. Access to RESTful APIs, no authentication Set the Consts.IS_AUTH_ENABLED to false Set the Consts.PROJECT_ID to
  • 21. Access to RESTful APIs, no authentication Google Cloud Endpoints automatically generates the Android code required to access the backend APIs Mobilebackend.Builder builder = new Mobilebackend.Builder( AndroidHttp.newCompatibleTransport(), new GsonFactory(), null); Mobilebackend backend = builder.setRootUrl(Consts.ENDPOINT_ROOT_URL).build();
  • 22. Access to RESTful APIs, no authentication Insert a new CloudEntity in the backend CloudEntity post = new CloudEntity("Guestbook"); post.put("message", "Your message here..."); EntityDto resultEntityDto = backend.endpointV1() .insert(post.getKindName(), post.getEntityDto()).execute(); CloudEntity resultCo = CloudEntity.createCloudEntityFromEntityDto (resultEntityDto); Log.i(Consts.TAG, "insert: inserted: " + resultCo);
  • 23. Step 2 Accessing to the APIs with authentication
  • 24. Authenticated access to the APIs Restrict the API access only to your application(s). ANDROID Client_ID: identifies your app in unique way (package name + SHA1 of signing key of the app) WEB Client_ID: establishes that the client and the server are from the same developer so the standard OAuth2 prompt is avoided (no 3rd party app). It’s a shared token. https://developers.google.com/appengine/docs/java/endpoints/auth
  • 29. Set Android and Web Client IDs in the backend
  • 30. Authenticated access to the APIs Set the Consts.IS_AUTH_ENABLED to true Set the Consts.WEB_CLIENT_ID to Web Client ID
  • 32. The Android client provides credentials! GoogleAccountCredential credential = GoogleAccountCredential.usingAudience( getActivity(), Consts.AUTH_AUDIENCE); if (credential.getSelectedAccountName() == null) { startActivityForResult( credential.newChooseAccountIntent(), REQUEST_ACCOUNT_PICKER); String accountName = data.getStringExtra(AccountManager.KEY_ACCOUNT_NAME); credential.setSelectedAccountName(accountName); https://developers.google. com/appengine/docs/java/endpoints/consume_android#Java_Making_aut henticated_calls
  • 33. Authenticated access to the APIs Inject the credential in the backend manager class // check if credential has account name final GoogleAccountCredential gac = credential == null || credential.getSelectedAccountName() == null ? null : mCredential; // create HttpRequestInitializer HttpRequestInitializer httpRequestInitializer = new HttpRequestInitializer() { @Override public void initialize(HttpRequest request) throws IOException { if (gac != null) { gac.initialize(request); } } };
  • 34. Authenticated access to the APIs Mobilebackend.Builder builder = new Mobilebackend.Builder( AndroidHttp.newCompatibleTransport(), new GsonFactory(), httpRequestInitializer); Mobilebackend backend = builder.setRootUrl(Consts.ENDPOINT_ROOT_URL).build(); … Now the API backend framework automatically authenticates the user and enforces the authorized clientIds whitelist, ultimately by supplying a valid User to the API parameters.
  • 35. Step 3 Add push notifications
  • 37. Google Cloud Messaging for Android http://developer.android.com/google/gcm/index.html
  • 38. Enable GCM in the project
  • 39. Generate a Server API Key
  • 40. Generate a Server API Key
  • 41. Enable GCM in the backend
  • 42. Enable GCM in the client Set the Consts.PROJECT_NUMBER to
  • 44. A look into GCM client code http://developer.android.com/google/gcm/client.html Register your app and store registration ID String regId = getRegIdFromPref(); if (registrationId.isEmpty()) { regid = GoogleCloudMessaging.getInstance(context) .register(PROJECT_ID); storeRegIdToPref(regId); }
  • 45. Create a BroadcastReceiver to receive push messages @Override public void onReceive(Context context, Intent intent) { // Explicitly specify that GcmIntentService will handle the intent ComponentName comp = new ComponentName( context.getPackageName(), GCMIntentService.class.getName()); // Start service, keeping the device awake while it is launching startWakefulService(context, (intent.setComponent(comp))); setResultCode(Activity.RESULT_OK); }
  • 46. Handle the message with a Service protected void onHandleIntent(Intent intent) { Bundle extras = intent.getExtras(); GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this); String msgType = gcm.getMessageType(intent); if (extras.isEmpty()) { // has effect of unparcelling Bundle … } if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE.equals(messageType)) { … } // Release the wake lock provided by the WakefulBroadcastReceiver. GCMBroadcastReceiver.completeWakefulIntent(intent); }
  • 47. And remember to... App registration is a network operation
  • 48. Bonus Step App internal architecture
  • 49. Because API calls are slow... EntityDto resultEntityDto = backend.endpointV1() .insert(post.getKindName(), post.getEntityDto()).execute();
  • 51. CloudBackendASync extends CloudBackend // create a response handler that will receive the result or an error CloudCallbackHandler<List<CloudEntity>> handler = new CloudCallbackHandler<List<CloudEntity>>() { @Override public void onComplete(List<CloudEntity> results) { ... } @Override public void onError(IOException exception) { ... }
  • 52. CloudBackendASync extends CloudBackend // execute the query with the handler mProcessingFragment.getCloudBackend().listByKind( "Guestbook", CloudEntity.PROP_CREATED_AT, Order.DESC, 50, Scope.FUTURE_AND_PAST, handler);
  • 53. Why these two classes? Separate the logic (CloudBackend) from the sync management (CloudBackendAsync) makes the code more testable!
  • 54. Activity lifecycle (you can do better!) // Check to see if we have retained the fragment which handles asynchronous backend calls mProcessingFragment = (CloudBackendFragment) mFragmentManager. findFragmentByTag(PROCESSING_FRAGMENT_TAG); // If not retained (or first time running), create a new one if (mProcessingFragment == null) { mProcessingFragment = new CloudBackendFragment(); mProcessingFragment.setRetainInstance(true); fragmentTransaction.add(mProcessingFragment, PROCESSING_FRAGMENT_TAG); } … // execute the insertion with the handler mProcessingFragment.getCloudBackend().insert(newPost, handler); mMessageTxt.setEnabled(false); mSendBtn.setEnabled(false);
  • 55. Extends the data CloudEntity post = new CloudEntity("Guestbook"); post.put("message", "Your message here..."); post.put("alf_property", "Custom property value here..."); EntityDto resultEntityDto = backend.endpointV1() .insert(post.getKindName(), post.getEntityDto()).execute(); CloudEntity resultCo = CloudEntity.createCloudEntityFromEntityDto(resultEntityDto);
  • 56. Curious about Google dev initiatives and event in Italy? https://developersitalia.blogspot.com