Google Fit for Android is part of Google Play services.

Google Fit SDK consists of History API, Sensors API, Recording API, Sessions API and Bluetooth Low energy API.

At this point, you might be wondering ‘what is an api?’. Follow the link for an in-depth explanation, but it is a software that allows two separate applications to work together. Google Fit API in Android provides all the features available in Google Fit official Android app.

This article will cover how to connect with Google Fit API and how to record user health data

using History API in Google fit SDK for Android.

This tutorial focuses on saving distance, calories burned, start time, end time of a user activity using Google Fit History API.

We will learn how to use Google play services Android sdk and store user data in Google Fitness API

for later use.

Fitness data stored using Fitness API can be accessed from any device whether it be Android Wear, iOS or web app.

Getting Started

Google Fit API for Android required OAuth2.0 id.

I assume you have created a project at Google console and you are done with Oauth2.0 part also.

Make sure Google Play services and Google Repository packages are installed in Android SDK.

Step 1:

Add Google Fitness and Google Auth dependencies in build.gradle file.

 implementation ''
 implementation ''

Step 2:

Before you can use Google Fit API methods you need to connect with Google Fit .

You need to provide Data Types and Scope before accessing Google Fit API.

Than Google Fit will ask user to allow access to your application to read/write your fitness data from your account.

 private void buildFitnessClient() {
     FitnessOptions fitnessOptions = FitnessOptions.builder()
             .addDataType(DataType.TYPE_LOCATION_SAMPLE, FitnessOptions.ACCESS_WRITE)
             .addDataType(DataType.TYPE_ACTIVITY_SEGMENT, FitnessOptions.ACCESS_WRITE)
     Scope scopeLocation = new Scope(Scopes.FITNESS_LOCATION_READ_WRITE);
     Scope scopesActivity = new Scope(Scopes.FITNESS_ACTIVITY_READ_WRITE);
     if (!GoogleSignIn.hasPermissions(GoogleSignIn.getLastSignedInAccount(this), fitnessOptions)) {
                 this, // your activity
                 scopesActivity, scopeLocation);
     } else {

Because we need to save distance travelled, calories burned data so we need FITNESS_ACTIVITY_READ_WRITE and FITNESS_LOCATION_READ_WRITE permissions from user.

At this step user will see following screen.

Google Fit request user permission
Google Fit API Authentication

Now add onActivityResult override method to handle user response to your requst. If user grant permission to your application for accessing Google Fit data or not this will be called.

 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
     if (resultCode == Activity.RESULT_OK) {
         if (requestCode == GOOGLE_FIT_PERMISSIONS_REQUEST_CODE) {

If user granted access to your application. You can now connect with Google Fit. Now assuming user has authorized access to read write Fitness History data. We will build GoogleApiClient for saving fitness data.

 private void accessGoogleFit() {
     Log.d(LogTheRunActivity.this.getLocalClassName(), "authorized");
     if (mFitnessClient == null) {
         mFitnessClient = new GoogleApiClient.Builder(this)
                 .addScope(new Scope(Scopes.FITNESS_LOCATION_READ_WRITE))
                 .addScope(new Scope(Scopes.FITNESS_ACTIVITY_READ_WRITE))
                         new GoogleApiClient.ConnectionCallbacks() {
                             public void onConnected(Bundle bundle) {
                                 Log.i(LogTheRunActivity.this.getLocalClassName(), "Fitness Connected!!!");
                                 // Now you can make calls to the Fitness APIs.
                             public void onConnectionSuspended(int i) {
                                 // If your connection to the sensor gets lost at some point,
                                 // you'll be able to determine the reason and react to it here.
                                 if (i == GoogleApiClient.ConnectionCallbacks.CA-- USE_NETWORK_LOST) {
                                     Log.i(LogTheRunActivity.this.getLocalClassName(), "Connection lost.  Cause: Network Lost.");
                                 } else if (i == GoogleApiClient.ConnectionCallbacks.CA-- USE_SERVICE_DISCONNECTED) {
                                             "Connection lost.  Reason: Service Disconnected");
                 .enableAutoManage(this, 0, new GoogleApiClient.OnConnectionFailedListener() {
                     public void onConnectionFailed(ConnectionResult result) {
                         Log.i(LogTheRunActivity.this.getLocalClassName(), "Google Play services connection failed. Cause: " +
                                 "Exception while connecting to Google Play services: " +


Now we have to save user activity start time, end time, calories burned and distance covered we will use below code.

This is the case when user has runned and your application needs to save run details in Google Fit API.

 private final String SESSION_NAME = "LogRunActivity";
 SessionInsertRequest insertRequest; 
 private void addUserDataAndroidHealth() {
    mSession = new Session.Builder()
             .setIdentifier(getString(R.string.app_name) + " " + System.currentTimeMillis())
             .setDescription("Running Session Details")
             .setStartTime((long) startTime, TimeUnit.MILLISECONDS)
             .setEndTime((long) endTime, TimeUnit.MILLISECONDS)
     DataSource distanceSegmentDataSource = new DataSource.Builder()
             .setName("Total Distance Covered")
     DataSet distanceDataSet = DataSet.create(distanceSegmentDataSource);
     DataPoint firstRunSpeedDataPoint = distanceDataSet.createDataPoint()
             .setTimeInterval((long) startTime, (long) endTime, TimeUnit.MILLISECONDS);
     firstRunSpeedDataPoint.getValue(Field.FIELD_DISTANCE).setFloat((float) totalCoveredDistanceInMiles);
     DataSource caloriesDataSource = new DataSource.Builder()
             .setName("Total Calories Burned")
     DataSet caloriesDataSet = DataSet.create(caloriesDataSource);
     DataPoint caloriesDataPoint = caloriesDataSet.createDataPoint()
             .setTimeInterval((long) startTime, (long) endTime, TimeUnit.MILLISECONDS);
     caloriesDataPoint.getValue(Field.FIELD_CALORIES).setFloat((float) totalCalories);
     insertRequest = new SessionInsertRequest.Builder()
     new InsertIUserHistoryDataGoogleFit().execute("", "", "");

As Google Fit API will execute a network call for writing user data to Fitness History API. We will not call this code on main thread instead we will write Async Task.

 private class InsertIUserHistoryDataGoogleFit extends AsyncTask {
     protected String doInBackground(String... urls) {
         pendingResult =
                 Fitness.SessionsApi.insertSession(mFitnessClient, insertRequest);
         pendingResult.setResultCallback(new ResultCallback() {
             public void onResult( status) {
                 insertStatus = status;
                 if (status.isSuccess()) {           // -- USER RECORD INSERTED SUCCESSFULLY.
                                   } else {
                     Log.i(LogTheRunActivity.this.getLocalClassName(), "Failed to insert running session: " + status.getStatusMessage());
         return "";
     protected void onProgressUpdate(Integer... progress) {
     protected void onPostExecute(String result) {

22 Responses

  1. Wonderful blog! I found it while browsing on Yahoo News.
    Do you have any suggestions on how to get listed in Yahoo
    News? I’ve been trying for a while but I never seem to get there!
    Appreciate it

  2. Have you ever considered writing an e-book or
    guest authoring on other sites? I have a blog centered
    on the same ideas you discuss and would love to have you share some stories/information. I
    know my visitors would appreciate your work. If you are even remotely interested, feel
    free to shoot me an e mail.

  3. Having read this I thought it was really informative. I appreciate you finding the time and energy
    to put this informative article together. I once again find
    myself spending way too much time both reading and
    leaving comments. But so what, it was still worth it!

  4. Woah! I’m really digging the template/theme of this site.
    It’s simple, yet effective. A lot of times it’s very difficult to
    get that “perfect balance” between user friendliness and visual appearance.
    I must say you have done a great job with this.
    In addition, the blog loads extremely quick for me on Opera.
    Excellent Blog!

  5. Thanks for a marvelous posting! I definitely enjoyed reading it, you are a great author.
    I will make sure to bookmark your blog and will
    come back later in life. I want to encourage you to ultimately continue your great
    writing, have a nice weekend!

  6. I’m not sure where you’re getting your information,
    but great topic. I needs to spend some time learning more or understanding more.

    Thanks for wonderful information I was looking for this info for my mission.

  7. Howdy! This post couldn’t be written any better! Reading this post reminds me of my good old room mate!
    He always kept talking about this. I will forward this post to him.
    Fairly certain he will have a good read. Many thanks
    for sharing!

  8. Great weblog right here! Also your site a lot up very fast!
    What web host are you the use of? Can I get your affiliate link in your host?

    I wish my site loaded up as fast as yours lol

  9. Pretty section of content. I just stumbled upon your website and in accession capital to say that
    I get actually loved account your blog posts.
    Anyway I’ll be subscribing on your augment or even I success you get right of entry to persistently quickly.

  10. Hey this is kind of of off topic but I was wanting
    to know if blogs use WYSIWYG editors or if you have to manually code with HTML.
    I’m starting a blog soon but have no coding expertise so I wanted to get guidance from
    someone with experience. Any help would be greatly appreciated!

  11. Link exchange is nothing else except it is just placing the other person’s blog link on your page at suitable place
    and other person will also do same in favor of you.

  12. I needed to thank you for this excellent read!!
    I certainly loved every bit of it. I have you bookmarked to check out new things you post…

  13. Very nice tutorial! Would it be possible to update it for GoogleApi client ? It says in the documentation:
    GoogleApi client is easier to use than its predecessor (GoogleApiClient used in this project), since it automatically manages connections to Google Play services.

    1. I will try to manage some time and update it according to google API. But other than this it will be the same. So you can also update it by yourself.

  14. Hello There. I discovered your weblog the usage of msn. That is an extremely
    smartly written article. I will make sure to bookmark
    it and come back to learn more of your useful
    info. Thank you for the post. I’ll certainly comeback.

  15. I’m not sure where you are getting your info, but great topic.
    I needs to spend some time learning much more or understanding more.
    Thanks for excellent information I was looking for this information for my mission.