Integrating GoogleFit into Android Apps

Integrating GoogleFit into
Android Apps
Tokyo Android Meetup 21st December 2016
About The Presenter
Giles Payne
Senior Android Developer - TenTen Corp
Developing for Android since Cupcake
BA Honours Mathematics and Computation, Oxford University
Country of Origin: Scotland
About the Green+ App
https://play.google.com/store/apps/details?id=com.mytenten.sunpo&hl=jp
Implementing the Walking Point feature
iOS - HealthKit
Android - GoogleFit
Integrating GoogleFit into an Android app
Get an API Key/Register your app's package on the Google
API Console
Add dependency to build.gradle
Create the Google API Client
Call enableAutoManage
Subscribe to a data source
Query the data source!!
Get an API key
Get the key from: https://console.developers.google.com/flows/enableapi?apiid=fitness&pli=1
Follow the instructions at: https://developers.google.com/fit/android/get-api-key
You don't actually need to do anything with the key.
Just being registered is enough
Add dependency to build.gradle
dependencies {
...
compile 'com.google.android.gms:play-services-fitness:10.0.0'
...
}
Create the Google API Client
GoogleApiClient googleApiClient = new GoogleApiClient.Builder(TenTenApp.getAppContext())
.addApi(Fitness.RECORDING_API)
.addApi(Fitness.HISTORY_API)
.addScope(new Scope(Scopes.FITNESS_ACTIVITY_READ))
…
…
.build();
Depending on what you want to do you may need different APIs (for example
SENSORS_API) or different scopes (for example FITNESS_ACTIVITY_READ_WRITE)
https://developers.google.com/android/reference/com/google/android/gms/common/api/GoogleApiClient
Call enableAutoManage
GoogleApiClient googleApiClient = new GoogleApiClient.Builder(TenTenApp.getAppContext())
…
.enableAutoManage(fragmentActivity, 0, new GoogleApiClient.OnConnectionFailedListener() {
@Override
public void onConnectionFailed(ConnectionResult result) {
if (result.getErrorCode() == ConnectionResult.CANCELED) {
cancelled = true;
}
}
})
.build();
enableAutoManage handles a lot of things - including
● Requesting user permission to use the service
● Selection of a Google account with which to associate the fitness data
● Installation of any required software that is missing (Google Play Developer Services)
https://developers.google.com/android/reference/com/google/android/gms/common/api/GoogleApiClient.Builder.html
#enableAutoManage(android.support.v4.app.FragmentActivity,com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener)
Subscribe to a data source
Fitness.RecordingApi.subscribe(googleApiClient, DataType.TYPE_STEP_COUNT_DELTA)
.setResultCallback(new ResultCallback<Status>() {
@Override
public void onResult(Status status) {
if (status.isSuccess()) {
// subscribed successfully
} else {
// error subscribing
}
}
});
TYPE_STEP_COUNT_DELTA will report walking steps. For the full range of available
data types refer to:
https://developers.google.com/android/reference/com/google/android/gms/fitness/data/DataTyp
e
Query the data source!!
DataReadRequest dataReadRequest = new DataReadRequest.Builder()
.aggregate(DataType.TYPE_STEP_COUNT_DELTA, DataType.AGGREGATE_STEP_COUNT_DELTA)
.bucketByTime(1, TimeUnit.DAYS)
.setTimeRange(start, end, TimeUnit.MILLISECONDS)
.build();
AGGREGATE data types will generally be more useful however raw data types are also
available. Queries can be synchronous or asynchronous.
https://developers.google.com/android/reference/com/google/android/gms/fitness/data/DataTyp
e
Process the query results
for (Bucket bucket : dataReadResult.getBuckets()) {
List<DataSet> dataSets = bucket.getDataSets();
for (DataSet dataSet : dataSets) {
for (DataPoint dataPoint : dataSet.getDataPoints()) {
if (dataPoint.getDataType().getName().equals(STEP_COUNT_DATA_TYPE)) {
for(Field field : dataPoint.getDataType().getFields()) {
if (field.getName().equals(STEP_COUNT_FIELD_NAME)) {
long dayStart = dataPoint.getStartTime(TimeUnit.MILLISECONDS);
int stepCount = dataPoint.getValue(field).asInt();
}
}
}
}
}
}
GoogleFit Gotchas
Where to put the API key
Nowhere!!
Reconnecting
In some cases you explicitly need to reconnect or handle a connection failed event.
If you don’t do this then data queries will start to fail after the app is open for longer 48 hour
1 of 13

Recommended

Android M - Getting Started by
Android M - Getting StartedAndroid M - Getting Started
Android M - Getting StartedEduardo Carrara de Araujo
646 views14 slides
How NOT to Suck at App Distribution - Quick Start Guide - Appsocially's Growt... by
How NOT to Suck at App Distribution - Quick Start Guide - Appsocially's Growt...How NOT to Suck at App Distribution - Quick Start Guide - Appsocially's Growt...
How NOT to Suck at App Distribution - Quick Start Guide - Appsocially's Growt...Yusuke Takahashi, PhD
1.1K views39 slides
Recap of the google io 2017 by
Recap of the google io 2017Recap of the google io 2017
Recap of the google io 2017Karan Trehan
145 views19 slides
Get started with watch kit development by
Get started with watch kit developmentGet started with watch kit development
Get started with watch kit developmentMindfire Solutions
1.2K views20 slides
Startup weekend bootcamp - Android up and running by
Startup weekend bootcamp - Android up and runningStartup weekend bootcamp - Android up and running
Startup weekend bootcamp - Android up and runningLance Nanek
1.4K views33 slides
How to create Github App for web applications by
How to create Github App for web applicationsHow to create Github App for web applications
How to create Github App for web applicationsthesoftwareguy7
1.7K views6 slides

More Related Content

What's hot

MapUp Tlemcen - Google Maps API by
MapUp Tlemcen - Google Maps APIMapUp Tlemcen - Google Maps API
MapUp Tlemcen - Google Maps APIMeryem Bendella
781 views27 slides
Google Apps Script Overview by
Google Apps Script OverviewGoogle Apps Script Overview
Google Apps Script Overviewtty fky
1.9K views16 slides
Gae by
GaeGae
GaeWen chi ching
913 views10 slides
Android App Development 20150402 by
Android App Development 20150402Android App Development 20150402
Android App Development 20150402Hideo Kadowaki
686 views15 slides
API as a Growth Tool by
API as a Growth ToolAPI as a Growth Tool
API as a Growth Tool3scale
2.7K views59 slides
Hacking the browser with puppeteer sharp .NET conf AR 2018 by
Hacking the browser with puppeteer sharp .NET conf AR 2018Hacking the browser with puppeteer sharp .NET conf AR 2018
Hacking the browser with puppeteer sharp .NET conf AR 2018Darío Kondratiuk
829 views35 slides

What's hot(17)

Google Apps Script Overview by tty fky
Google Apps Script OverviewGoogle Apps Script Overview
Google Apps Script Overview
tty fky1.9K views
Android App Development 20150402 by Hideo Kadowaki
Android App Development 20150402Android App Development 20150402
Android App Development 20150402
Hideo Kadowaki686 views
API as a Growth Tool by 3scale
API as a Growth ToolAPI as a Growth Tool
API as a Growth Tool
3scale2.7K views
Hacking the browser with puppeteer sharp .NET conf AR 2018 by Darío Kondratiuk
Hacking the browser with puppeteer sharp .NET conf AR 2018Hacking the browser with puppeteer sharp .NET conf AR 2018
Hacking the browser with puppeteer sharp .NET conf AR 2018
Darío Kondratiuk829 views
Applying Design Priciples to APIs - 1 of 4 by Brian Mulloy
Applying Design Priciples to APIs - 1 of 4Applying Design Priciples to APIs - 1 of 4
Applying Design Priciples to APIs - 1 of 4
Brian Mulloy2.7K views
Atomic Designは「マルチ」で真価を発揮する by Yukiya Nakagawa
Atomic Designは「マルチ」で真価を発揮するAtomic Designは「マルチ」で真価を発揮する
Atomic Designは「マルチ」で真価を発揮する
Yukiya Nakagawa2.4K views
Two Ton API Client by Brian Mulloy
Two Ton API ClientTwo Ton API Client
Two Ton API Client
Brian Mulloy1.2K views
LF_APIStrat17_Getting Your API House In Order by LF_APIStrat
LF_APIStrat17_Getting Your API House In OrderLF_APIStrat17_Getting Your API House In Order
LF_APIStrat17_Getting Your API House In Order
LF_APIStrat101 views
Android App Development 20150409 by Hideo Kadowaki
Android App Development 20150409Android App Development 20150409
Android App Development 20150409
Hideo Kadowaki747 views
GeoLocal APIs: unencumbering the geolocal ecosystem by Tyler Bell
GeoLocal APIs: unencumbering the geolocal ecosystemGeoLocal APIs: unencumbering the geolocal ecosystem
GeoLocal APIs: unencumbering the geolocal ecosystem
Tyler Bell575 views

Viewers also liked

Mejorando estrategias pedagógicas para la inclusión de personas con discapaci... by
Mejorando estrategias pedagógicas para la inclusión de personas con discapaci...Mejorando estrategias pedagógicas para la inclusión de personas con discapaci...
Mejorando estrategias pedagógicas para la inclusión de personas con discapaci...Maria Rosario Carrasco Patzi
476 views24 slides
PIP by
PIPPIP
PIPJosé Ignacio Prieto
156 views5 slides
Graficos diario del ibex,eurostoxx,s&p,dax y eurodolar 26 07 2011 by
Graficos diario del ibex,eurostoxx,s&p,dax y eurodolar 26 07 2011Graficos diario del ibex,eurostoxx,s&p,dax y eurodolar 26 07 2011
Graficos diario del ibex,eurostoxx,s&p,dax y eurodolar 26 07 2011Experiencia Trading
151 views4 slides
History of the nethelands by
History of the nethelandsHistory of the nethelands
History of the nethelandsAnnabel BP
158 views20 slides
Eurostat production industrielle en baisse by
Eurostat production industrielle en baisseEurostat production industrielle en baisse
Eurostat production industrielle en baisseSociété Tripalio
136 views6 slides
TICS.1 by
TICS.1TICS.1
TICS.1Jessica Duque
171 views3 slides

Similar to Integrating GoogleFit into Android Apps

Google Plus SignIn : l'Authentification Google by
Google Plus SignIn : l'Authentification GoogleGoogle Plus SignIn : l'Authentification Google
Google Plus SignIn : l'Authentification GoogleMathias Seguy
3.1K views57 slides
Let's your users share your App with Friends: App Invites for Android by
 Let's your users share your App with Friends: App Invites for Android Let's your users share your App with Friends: App Invites for Android
Let's your users share your App with Friends: App Invites for AndroidWilfried Mbouenda Mbogne
535 views57 slides
Exploring the Google Analytics API by
Exploring the Google Analytics APIExploring the Google Analytics API
Exploring the Google Analytics APIVanessa Sabino
7.5K views31 slides
YouTube APIs Workshop by
YouTube APIs WorkshopYouTube APIs Workshop
YouTube APIs WorkshopJarek Wilkiewicz
2.3K views22 slides
Google analytics by
Google analyticsGoogle analytics
Google analyticsSean Tsai
39 views41 slides
Android Google Fit by
Android Google FitAndroid Google Fit
Android Google FitYuki Nanri
1.1K views28 slides

Similar to Integrating GoogleFit into Android Apps(20)

Google Plus SignIn : l'Authentification Google by Mathias Seguy
Google Plus SignIn : l'Authentification GoogleGoogle Plus SignIn : l'Authentification Google
Google Plus SignIn : l'Authentification Google
Mathias Seguy3.1K views
Let's your users share your App with Friends: App Invites for Android by Wilfried Mbouenda Mbogne
 Let's your users share your App with Friends: App Invites for Android Let's your users share your App with Friends: App Invites for Android
Let's your users share your App with Friends: App Invites for Android
Exploring the Google Analytics API by Vanessa Sabino
Exploring the Google Analytics APIExploring the Google Analytics API
Exploring the Google Analytics API
Vanessa Sabino7.5K views
Google analytics by Sean Tsai
Google analyticsGoogle analytics
Google analytics
Sean Tsai39 views
Android Google Fit by Yuki Nanri
Android Google FitAndroid Google Fit
Android Google Fit
Yuki Nanri1.1K views
Recap of Android Dev Summit 2018 by Hassan Abid
Recap of Android Dev Summit 2018Recap of Android Dev Summit 2018
Recap of Android Dev Summit 2018
Hassan Abid414 views
Introduction to Digital Analytics for Apps - Trusted Conf by In Marketing We Trust
Introduction to Digital Analytics for Apps - Trusted ConfIntroduction to Digital Analytics for Apps - Trusted Conf
Introduction to Digital Analytics for Apps - Trusted Conf
Mobile backends with Google Cloud Platform (MBLTDev'14) by Natalia Efimtseva
Mobile backends with Google Cloud Platform (MBLTDev'14)Mobile backends with Google Cloud Platform (MBLTDev'14)
Mobile backends with Google Cloud Platform (MBLTDev'14)
Natalia Efimtseva515 views
Cómo tener analíticas en tu app y no volverte loco by Gemma Del Olmo
Cómo tener analíticas en tu app y no volverte locoCómo tener analíticas en tu app y no volverte loco
Cómo tener analíticas en tu app y no volverte loco
Gemma Del Olmo207 views
AnDevCon - Tracking User Behavior Creatively by Kiana Tennyson
AnDevCon - Tracking User Behavior CreativelyAnDevCon - Tracking User Behavior Creatively
AnDevCon - Tracking User Behavior Creatively
Kiana Tennyson2.5K views
Fraudpointer - Google Apps integration by Fraudpointer.com
Fraudpointer  - Google Apps integrationFraudpointer  - Google Apps integration
Fraudpointer - Google Apps integration
Fraudpointer.com1.6K views
[Android] Google Service Play & Google Maps by Natã Melo
[Android] Google Service Play & Google Maps[Android] Google Service Play & Google Maps
[Android] Google Service Play & Google Maps
Natã Melo895 views
Cross-Platform Authentication with Google+ Sign-In by Peter Friese
Cross-Platform Authentication with Google+ Sign-InCross-Platform Authentication with Google+ Sign-In
Cross-Platform Authentication with Google+ Sign-In
Peter Friese3.8K views
Introduction to Firebase [Google I/O Extended Bangkok 2016] by Sittiphol Phanvilai
Introduction to Firebase [Google I/O Extended Bangkok 2016]Introduction to Firebase [Google I/O Extended Bangkok 2016]
Introduction to Firebase [Google I/O Extended Bangkok 2016]
Sittiphol Phanvilai10.7K views
Introduction to Cloud Computing with Google Cloud by wesley chun
Introduction to Cloud Computing with Google CloudIntroduction to Cloud Computing with Google Cloud
Introduction to Cloud Computing with Google Cloud
wesley chun354 views
Testing android apps with espresso by Édipo Souza
Testing android apps with espressoTesting android apps with espresso
Testing android apps with espresso
Édipo Souza11.6K views
Google Integration in Android Apps - Mooscon 2013 Cebit by Friedger Müffke
Google Integration in Android Apps - Mooscon 2013 CebitGoogle Integration in Android Apps - Mooscon 2013 Cebit
Google Integration in Android Apps - Mooscon 2013 Cebit
Friedger Müffke912 views
Google cloud platform by rajdeep
Google cloud platformGoogle cloud platform
Google cloud platform
rajdeep7.4K views

Recently uploaded

2023Dec ASU Wang NETR Group Research Focus and Facility Overview.pptx by
2023Dec ASU Wang NETR Group Research Focus and Facility Overview.pptx2023Dec ASU Wang NETR Group Research Focus and Facility Overview.pptx
2023Dec ASU Wang NETR Group Research Focus and Facility Overview.pptxlwang78
165 views19 slides
Pitchbook Repowerlab.pdf by
Pitchbook Repowerlab.pdfPitchbook Repowerlab.pdf
Pitchbook Repowerlab.pdfVictoriaGaleano
5 views12 slides
dummy.pptx by
dummy.pptxdummy.pptx
dummy.pptxJamesLamp
5 views2 slides
GDSC Mikroskil Members Onboarding 2023.pdf by
GDSC Mikroskil Members Onboarding 2023.pdfGDSC Mikroskil Members Onboarding 2023.pdf
GDSC Mikroskil Members Onboarding 2023.pdfgdscmikroskil
59 views62 slides
sam_software_eng_cv.pdf by
sam_software_eng_cv.pdfsam_software_eng_cv.pdf
sam_software_eng_cv.pdfsammyigbinovia
9 views5 slides
Searching in Data Structure by
Searching in Data StructureSearching in Data Structure
Searching in Data Structureraghavbirla63
14 views8 slides

Recently uploaded(20)

2023Dec ASU Wang NETR Group Research Focus and Facility Overview.pptx by lwang78
2023Dec ASU Wang NETR Group Research Focus and Facility Overview.pptx2023Dec ASU Wang NETR Group Research Focus and Facility Overview.pptx
2023Dec ASU Wang NETR Group Research Focus and Facility Overview.pptx
lwang78165 views
GDSC Mikroskil Members Onboarding 2023.pdf by gdscmikroskil
GDSC Mikroskil Members Onboarding 2023.pdfGDSC Mikroskil Members Onboarding 2023.pdf
GDSC Mikroskil Members Onboarding 2023.pdf
gdscmikroskil59 views
Searching in Data Structure by raghavbirla63
Searching in Data StructureSearching in Data Structure
Searching in Data Structure
raghavbirla6314 views
Ansari: Practical experiences with an LLM-based Islamic Assistant by M Waleed Kadous
Ansari: Practical experiences with an LLM-based Islamic AssistantAnsari: Practical experiences with an LLM-based Islamic Assistant
Ansari: Practical experiences with an LLM-based Islamic Assistant
M Waleed Kadous7 views
Créativité dans le design mécanique à l’aide de l’optimisation topologique by LIEGE CREATIVE
Créativité dans le design mécanique à l’aide de l’optimisation topologiqueCréativité dans le design mécanique à l’aide de l’optimisation topologique
Créativité dans le design mécanique à l’aide de l’optimisation topologique
LIEGE CREATIVE5 views
Design of Structures and Foundations for Vibrating Machines, Arya-ONeill-Pinc... by csegroupvn
Design of Structures and Foundations for Vibrating Machines, Arya-ONeill-Pinc...Design of Structures and Foundations for Vibrating Machines, Arya-ONeill-Pinc...
Design of Structures and Foundations for Vibrating Machines, Arya-ONeill-Pinc...
csegroupvn6 views
MongoDB.pdf by ArthyR3
MongoDB.pdfMongoDB.pdf
MongoDB.pdf
ArthyR349 views
Design of machine elements-UNIT 3.pptx by gopinathcreddy
Design of machine elements-UNIT 3.pptxDesign of machine elements-UNIT 3.pptx
Design of machine elements-UNIT 3.pptx
gopinathcreddy34 views
Web Dev Session 1.pptx by VedVekhande
Web Dev Session 1.pptxWeb Dev Session 1.pptx
Web Dev Session 1.pptx
VedVekhande13 views
REACTJS.pdf by ArthyR3
REACTJS.pdfREACTJS.pdf
REACTJS.pdf
ArthyR335 views
ASSIGNMENTS ON FUZZY LOGIC IN TRAFFIC FLOW.pdf by AlhamduKure
ASSIGNMENTS ON FUZZY LOGIC IN TRAFFIC FLOW.pdfASSIGNMENTS ON FUZZY LOGIC IN TRAFFIC FLOW.pdf
ASSIGNMENTS ON FUZZY LOGIC IN TRAFFIC FLOW.pdf
AlhamduKure6 views
BCIC - Manufacturing Conclave - Technology-Driven Manufacturing for Growth by Innomantra
BCIC - Manufacturing Conclave -  Technology-Driven Manufacturing for GrowthBCIC - Manufacturing Conclave -  Technology-Driven Manufacturing for Growth
BCIC - Manufacturing Conclave - Technology-Driven Manufacturing for Growth
Innomantra 10 views

Integrating GoogleFit into Android Apps

  • 1. Integrating GoogleFit into Android Apps Tokyo Android Meetup 21st December 2016
  • 2. About The Presenter Giles Payne Senior Android Developer - TenTen Corp Developing for Android since Cupcake BA Honours Mathematics and Computation, Oxford University Country of Origin: Scotland
  • 3. About the Green+ App https://play.google.com/store/apps/details?id=com.mytenten.sunpo&hl=jp
  • 4. Implementing the Walking Point feature iOS - HealthKit Android - GoogleFit
  • 5. Integrating GoogleFit into an Android app Get an API Key/Register your app's package on the Google API Console Add dependency to build.gradle Create the Google API Client Call enableAutoManage Subscribe to a data source Query the data source!!
  • 6. Get an API key Get the key from: https://console.developers.google.com/flows/enableapi?apiid=fitness&pli=1 Follow the instructions at: https://developers.google.com/fit/android/get-api-key You don't actually need to do anything with the key. Just being registered is enough
  • 7. Add dependency to build.gradle dependencies { ... compile 'com.google.android.gms:play-services-fitness:10.0.0' ... }
  • 8. Create the Google API Client GoogleApiClient googleApiClient = new GoogleApiClient.Builder(TenTenApp.getAppContext()) .addApi(Fitness.RECORDING_API) .addApi(Fitness.HISTORY_API) .addScope(new Scope(Scopes.FITNESS_ACTIVITY_READ)) … … .build(); Depending on what you want to do you may need different APIs (for example SENSORS_API) or different scopes (for example FITNESS_ACTIVITY_READ_WRITE) https://developers.google.com/android/reference/com/google/android/gms/common/api/GoogleApiClient
  • 9. Call enableAutoManage GoogleApiClient googleApiClient = new GoogleApiClient.Builder(TenTenApp.getAppContext()) … .enableAutoManage(fragmentActivity, 0, new GoogleApiClient.OnConnectionFailedListener() { @Override public void onConnectionFailed(ConnectionResult result) { if (result.getErrorCode() == ConnectionResult.CANCELED) { cancelled = true; } } }) .build(); enableAutoManage handles a lot of things - including ● Requesting user permission to use the service ● Selection of a Google account with which to associate the fitness data ● Installation of any required software that is missing (Google Play Developer Services) https://developers.google.com/android/reference/com/google/android/gms/common/api/GoogleApiClient.Builder.html #enableAutoManage(android.support.v4.app.FragmentActivity,com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener)
  • 10. Subscribe to a data source Fitness.RecordingApi.subscribe(googleApiClient, DataType.TYPE_STEP_COUNT_DELTA) .setResultCallback(new ResultCallback<Status>() { @Override public void onResult(Status status) { if (status.isSuccess()) { // subscribed successfully } else { // error subscribing } } }); TYPE_STEP_COUNT_DELTA will report walking steps. For the full range of available data types refer to: https://developers.google.com/android/reference/com/google/android/gms/fitness/data/DataTyp e
  • 11. Query the data source!! DataReadRequest dataReadRequest = new DataReadRequest.Builder() .aggregate(DataType.TYPE_STEP_COUNT_DELTA, DataType.AGGREGATE_STEP_COUNT_DELTA) .bucketByTime(1, TimeUnit.DAYS) .setTimeRange(start, end, TimeUnit.MILLISECONDS) .build(); AGGREGATE data types will generally be more useful however raw data types are also available. Queries can be synchronous or asynchronous. https://developers.google.com/android/reference/com/google/android/gms/fitness/data/DataTyp e
  • 12. Process the query results for (Bucket bucket : dataReadResult.getBuckets()) { List<DataSet> dataSets = bucket.getDataSets(); for (DataSet dataSet : dataSets) { for (DataPoint dataPoint : dataSet.getDataPoints()) { if (dataPoint.getDataType().getName().equals(STEP_COUNT_DATA_TYPE)) { for(Field field : dataPoint.getDataType().getFields()) { if (field.getName().equals(STEP_COUNT_FIELD_NAME)) { long dayStart = dataPoint.getStartTime(TimeUnit.MILLISECONDS); int stepCount = dataPoint.getValue(field).asInt(); } } } } } }
  • 13. GoogleFit Gotchas Where to put the API key Nowhere!! Reconnecting In some cases you explicitly need to reconnect or handle a connection failed event. If you don’t do this then data queries will start to fail after the app is open for longer 48 hour