Work with historical data

The History API lets your app perform bulk operations on the fettle store: reading, inserting, updating, and deleting historical health and wellness information. Apply the History API to practice the following:

  • Read health and wellness data that was inserted or recorded using other apps.
  • Import batch information into Google Fit.
  • Update data in Google Fit.
  • Delete historical data that your app previously stored.

To insert information that contains session metadata, use the Sessions API.

Read data

The post-obit sections cover how to read dissimilar kinds of amass data.

Read detailed and aggregate information

To read historical information, create a DataReadRequest instance.

Kotlin

// Read the data that'south been nerveless throughout the by week. val endTime = LocalDateTime.now().atZone(ZoneId.systemDefault()) val startTime = endTime.minusWeeks(1) Log.i(TAG, "Range Showtime: $startTime") Log.i(TAG, "Range End: $endTime")  val readRequest =     DataReadRequest.Builder()         // The information request can specify multiple information types to return,         // effectively combining multiple data queries into one call.         // This example demonstrates aggregating only one data blazon.         .aggregate(DataType.AGGREGATE_STEP_COUNT_DELTA)         // Analogous to a "Group Past" in SQL, defines how information should be         // aggregated.         // bucketByTime allows for a fourth dimension bridge, whereas bucketBySession allows         // bucketing by <a href="/fit/android/using-sessions">sessions</a>.         .bucketByTime(one, TimeUnit.DAYS)         .setTimeRange(startTime.toEpochSecond(), endTime.toEpochSecond(), TimeUnit.SECONDS)         .build()                      

Coffee

// Read the data that'due south been collected throughout the past calendar week. ZonedDateTime endTime = LocalDateTime.now().atZone(ZoneId.systemDefault()); ZonedDateTime startTime = endTime.minusWeeks(1); Log.i(TAG, "Range Showtime: $startTime"); Log.i(TAG, "Range End: $endTime");  DataReadRequest readRequest = new DataReadRequest.Architect()         // The data request tin specify multiple data types to return,         // effectively combining multiple data queries into one call.         // This case demonstrates aggregating only one data type.         .aggregate(DataType.AGGREGATE_STEP_COUNT_DELTA)         // Coordinating to a "Group By" in SQL, defines how data should exist         // aggregated.         // bucketByTime allows for a time bridge, while bucketBySession allows         // bucketing by sessions.         .bucketByTime(1, TimeUnit.DAYS)         .setTimeRange(startTime.toEpochSecond(), endTime.toEpochSecond(), TimeUnit.SECONDS)         .build();                      

The previous example uses aggregated data points, where each DataPoint represents the number of steps walked in a day. For this particular use case, aggregated data points have 2 advantages:

  • Your app and the fettle store commutation smaller amounts of information.
  • Your app doesn't have to aggregate the information manually.

Aggregate data for multiple activity types

Your app tin can employ data requests to call up many different types of data. The following instance shows how to create a DataReadRequest to get calories burned for each activity performed within the specified time range. The resulting information matches the calories per activity as reported in the Google Fit app, where each activity gets its own bucket of calorie data.

Kotlin

val readRequest = DataReadRequest.Builder()     .aggregate(DataType.AGGREGATE_CALORIES_EXPENDED)     .bucketByActivityType(1, TimeUnit.SECONDS)     .setTimeRange(startTime.toEpochSecond(), endTime.toEpochSecond(), TimeUnit.SECONDS)     .build()                      

Coffee

DataReadRequest readRequest = new DataReadRequest.Builder()         .aggregate(DataType.AGGREGATE_CALORIES_EXPENDED)         .bucketByActivityType(1, TimeUnit.SECONDS)         .setTimeRange(startTime.toEpochSecond(), endTime.toEpochSecond(), TimeUnit.SECONDS)         .build();                      

After you create a DataReadRequest instance, use the HistoryClient.readData() method to asynchronously read historical data.

The following instance demonstrates how to obtain the DataPoint instances from a DataSet:

Kotlin

Fitness.getHistoryClient(this, GoogleSignIn.getAccountForExtension(this, fitnessOptions))     .readData(readRequest)     .addOnSuccessListener { response ->         // The aggregate query puts datasets into buckets, so flatten into a         // unmarried list of datasets         for (dataSet in response.buckets.flatMap { it.dataSets }) {             dumpDataSet(dataSet)         }     }     .addOnFailureListener { east ->         Log.due west(TAG,"In that location was an error reading data from Google Fit", e)     }  fun dumpDataSet(dataSet: DataSet) {     Log.i(TAG, "Data returned for Information type: ${dataSet.dataType.name}")     for (dp in dataSet.dataPoints) {         Log.i(TAG,"Data betoken:")         Log.i(TAG,"\tType: ${dp.dataType.name}")         Log.i(TAG,"\tStart: ${dp.getStartTimeString()}")         Log.i(TAG,"\tEnd: ${dp.getEndTimeString()}")         for (field in dp.dataType.fields) {             Log.i(TAG,"\tField: ${field.name.toString()} Value: ${dp.getValue(field)}")         }     } }  fun DataPoint.getStartTimeString() = Instant.ofEpochSecond(this.getStartTime(TimeUnit.SECONDS))     .atZone(ZoneId.systemDefault())     .toLocalDateTime().toString()  fun DataPoint.getEndTimeString() = Instant.ofEpochSecond(this.getEndTime(TimeUnit.SECONDS))     .atZone(ZoneId.systemDefault())     .toLocalDateTime().toString()                      

Java

Fettle.getHistoryClient(this, GoogleSignIn.getAccountForExtension(this, fitnessOptions))         .readData(readRequest)         .addOnSuccessListener (response -> {             // The aggregate query puts datasets into buckets, and then convert to a             // single listing of datasets             for (Bucket saucepan : response.getBuckets()) {                 for (DataSet dataSet : saucepan.getDataSets()) {                     dumpDataSet(dataSet);                 }             }         })         .addOnFailureListener(e ->             Log.w(TAG, "There was an fault reading data from Google Fit", e));  }  private void dumpDataSet(DataSet dataSet) {     Log.i(TAG, "Data returned for Data type: ${dataSet.dataType.name}");     for (DataPoint dp : dataSet.getDataPoints()) {         Log.i(TAG,"Data point:");         Log.i(TAG,"\tType: ${dp.dataType.name}");         Log.i(TAG,"\tStart: ${dp.getStartTimeString()}");         Log.i(TAG,"\tEnd: ${dp.getEndTimeString()}");         for (Field field : dp.getDataType().getFields()) {             Log.i(TAG,"\tField: ${field.name.toString()} Value: ${dp.getValue(field)}");         }     } }   private String getStartTimeString() {     return Instant.ofEpochSecond(this.getStartTime(TimeUnit.SECONDS))         .atZone(ZoneId.systemDefault())         .toLocalDateTime().toString(); }  private String getEndTimeString() {     return Instant.ofEpochSecond(this.getEndTime(TimeUnit.SECONDS))             .atZone(ZoneId.systemDefault())             .toLocalDateTime().toString(); }                      

Read daily total information

Google Fit also provides uncomplicated access to the daily total of a specified data type. Apply the HistoryClient.readDailyTotal() method to recollect the information blazon that y'all specify as of midnight of the electric current day in the device'south electric current timezone. For case, laissez passer in the TYPE_STEP_COUNT_DELTA data blazon to this method to recall the daily full steps. You can laissez passer in an instantaneous data type that has an amass daily full. For more information on the supported data types, run into DataType.getAggregateType.

Google Fit doesn't require authorization to subscribe to TYPE_STEP_COUNT_DELTA updates from the HistoryClient.readDailyTotal() method when this method is called using the default account and no scopes are specified. This can be useful if you lot require step data for use in areas where y'all're unable to testify the permissions panel, for example on Clothing OS watch faces.

Users adopt to see consequent step counts across the Google Fit app, other apps, and Article of clothing OS watch faces, because this provides them with a consequent and reliable feel. To keep step counts consistent, subscribe to steps in the Google Fit platform from your app or lookout man confront, and and then update the count in onExitAmbient(). For more information on how to apply this data in a watch face, come across Watch face complications and the Android WatchFace sample awarding.

Insert data

To insert historical data, first create a DataSetexample:

Kotlin

// Declare that the data existence inserted was nerveless during the by hr. val endTime = LocalDateTime.now().atZone(ZoneId.systemDefault()) val startTime = endTime.minusHours(1)  // Create a data source val dataSource = DataSource.Builder()     .setAppPackageName(this)     .setDataType(DataType.TYPE_STEP_COUNT_DELTA)     .setStreamName("$TAG - step count")     .setType(DataSource.TYPE_RAW)     .build()  // For each information indicate, specify a start time, end time, and the // information value -- in this example, 950 new steps. val stepCountDelta = 950 val dataPoint =     DataPoint.builder(dataSource)         .setField(Field.FIELD_STEPS, stepCountDelta)         .setTimeInterval(startTime.toEpochSecond(), endTime.toEpochSecond(), TimeUnit.SECONDS)         .build()  val dataSet = DataSet.builder(dataSource)     .add together(dataPoint)     .build()                      

Java

// Declare that the data existence inserted was collected during the past 60 minutes. ZonedDateTime endTime = LocalDateTime.now().atZone(ZoneId.systemDefault()); ZonedDateTime startTime = endTime.minusHours(1);  // Create a data source DataSource dataSource = new DataSource.Builder()         .setAppPackageName(this)         .setDataType(DataType.TYPE_STEP_COUNT_DELTA)         .setStreamName("$TAG - step count")         .setType(DataSource.TYPE_RAW)         .build();  // For each data point, specify a offset time, end time, and the // data value -- in this case, 950 new steps. int stepCountDelta = 950; DataPoint dataPoint = DataPoint.builder(dataSource)         .setField(Field.FIELD_STEPS, stepCountDelta)         .setTimeInterval(startTime.toEpochSecond(), endTime.toEpochSecond(), TimeUnit.SECONDS)         .build();  DataSet dataSet = DataSet.builder(dataSource)         .add(dataPoint)         .build();                      

After y'all create a DataSet example, utilise the HistoryClient.insertData method to asynchronously add together this historical data.

Kotlin

Fitness.getHistoryClient(this, GoogleSignIn.getAccountForExtension(this, fitnessOptions))     .insertData(dataSet)     .addOnSuccessListener {         Log.i(TAG, "DataSet added successfully!")     }     .addOnFailureListener { e ->         Log.w(TAG, "There was an error adding the DataSet", due east)     }                      

Java

Fettle.getHistoryClient(this, GoogleSignIn.getAccountForExtension(this, fitnessOptions))         .insertData(dataSet)         .addOnSuccessListener (unused ->                 Log.i(TAG, "DataSet added successfully!"))         .addOnFailureListener(due east ->                 Log.w(TAG, "In that location was an fault adding the DataSet", e)); }                      

Manage alien data points

Each DataPoint in your app'southward DataSet must accept a startTime and an endTime that defines a unique interval inside that DataSet, with no overlap between DataPoint instances.

If your app attempts to insert a new DataPoint that conflicts with an existing DataPoint instance, the new DataPoint is discarded. To insert a new DataPoint that might overlap with existing data points, employ the HistoryClient.updateData method described in Update information.

A data point can't be inserted if its duration overlaps with any existing data  points

Figure 1. How the insertData() method handles new information points that disharmonize with an existing DataPoint.

Update data

Google Fit lets your app update historical health and wellness information it previously inserted. To add together historical data for a new DataSet, or to add new DataPoint instances that don't conflict with existing data points, utilize the HistoryApi.insertData method.

To update historical information, use the HistoryClient.updateData method. This method deletes any existing DataPoint instances that overlap with DataPoint instances added using this method.

To update historical health and health data, first create a DataSet instance:

Kotlin

// Declare that the historical data was collected during the past fifty minutes. val endTime = LocalDateTime.at present().atZone(ZoneId.systemDefault()) val startTime = endTime.minusMinutes(fifty)  // Create a data source val dataSource  = DataSource.Architect()     .setAppPackageName(this)     .setDataType(DataType.TYPE_STEP_COUNT_DELTA)     .setStreamName("$TAG - pace count")     .setType(DataSource.TYPE_RAW)     .build()  // Create a data set // For each data indicate, specify a get-go time, end fourth dimension, and the // data value -- in this case, 1000 new steps. val stepCountDelta = 1000  val dataPoint = DataPoint.architect(dataSource)     .setTimeInterval(startTime.toEpochSecond(), endTime.toEpochSecond(), TimeUnit.SECONDS)     .setField(Field.FIELD_STEPS, stepCountDelta)     .build()  val dataSet = DataSet.architect(dataSource)     .add(dataPoint)     .build()                      

Coffee

// Declare that the historical data was collected during the past 50 minutes. ZonedDateTime endTime = LocalDateTime.at present().atZone(ZoneId.systemDefault()); ZonedDateTime startTime = endTime.minusMinutes(50);  // Create a data source DataSource dataSource = new DataSource.Architect()         .setAppPackageName(this)         .setDataType(DataType.TYPE_STEP_COUNT_DELTA)         .setStreamName("$TAG - step count")         .setType(DataSource.TYPE_RAW)         .build();  // Create a data fix // For each information point, specify a starting time time, end fourth dimension, and the // information value -- in this case, 1000 new steps. int stepCountDelta = 1000;  DataPoint dataPoint = DataPoint.architect(dataSource)         .setTimeInterval(startTime.toEpochSecond(), endTime.toEpochSecond(), TimeUnit.SECONDS)         .setField(Field.FIELD_STEPS, stepCountDelta)         .build();  DataSet dataSet = DataSet.builder(dataSource)         .add(dataPoint)         .build();                      

Then, use DataUpdateRequest.Builder() to create a new data update request, and employ the HistoryClient.updateData method to make the request:

Kotlin

val asking = DataUpdateRequest.Builder()     .setDataSet(dataSet)     .setTimeInterval(startTime.toEpochSecond(), endTime.toEpochSecond(), TimeUnit.SECONDS)     .build()  Fitness.getHistoryClient(this, GoogleSignIn.getAccountForExtension(this, fitnessOptions))     .updateData(asking)     .addOnSuccessListener {         Log.i(TAG, "DataSet updated successfully!")     }     .addOnFailureListener { east ->         Log.w(TAG, "There was an error updating the DataSet", due east)     }                      

Java

DataUpdateRequest request = new DataUpdateRequest.Builder()         .setDataSet(dataSet)         .setTimeInterval(startTime.toEpochSecond(), endTime.toEpochSecond(), TimeUnit.SECONDS)         .build();  Fitness.getHistoryClient(this, GoogleSignIn.getAccountForExtension(this, fitnessOptions))         .updateData(request)         .addOnSuccessListener(unused ->                 Log.i(TAG, "DataSet updated successfully!"))         .addOnFailureListener(e ->                 Log.w(TAG, "There was an error updating the DataSet", eastward));                      

Delete data

Google Fit lets your app delete historical health and wellness data it previously inserted.

To delete historical data, use the HistoryClient.deleteData method:

Kotlin

// Declare that this lawmaking deletes stride count information that was collected // throughout the past day. val endTime = LocalDateTime.now().atZone(ZoneId.systemDefault()) val startTime = endTime.minusDays(one)  // Create a delete request object, providing a information type and a time interval val request = DataDeleteRequest.Builder()     .setTimeInterval(startTime.toEpochSecond(), endTime.toEpochSecond(), TimeUnit.SECONDS)     .addDataType(DataType.TYPE_STEP_COUNT_DELTA)     .build()  // Invoke the History API with the HistoryClient object and delete request, and // so specify a callback that volition check the consequence. Fettle.getHistoryClient(this, GoogleSignIn.getAccountForExtension(this, fitnessOptions))     .deleteData(asking)     .addOnSuccessListener {         Log.i(TAG, "Data deleted successfully!")     }     .addOnFailureListener { east ->         Log.west(TAG, "In that location was an mistake with the deletion request", due east)     }                      

Java

// Declare that this lawmaking deletes stride count information that was collected // throughout the past day. ZonedDateTime endTime = LocalDateTime.now().atZone(ZoneId.systemDefault()); ZonedDateTime startTime = endTime.minusDays(i);  // Create a delete asking object, providing a data type and a fourth dimension interval DataDeleteRequest request = new DataDeleteRequest.Builder()         .setTimeInterval(startTime.toEpochSecond(), endTime.toEpochSecond(), TimeUnit.SECONDS)         .addDataType(DataType.TYPE_STEP_COUNT_DELTA)         .build();  // Invoke the History API with the HistoryClient object and delete request, and // and then specify a callback that volition cheque the result. Fitness.getHistoryClient(this, GoogleSignIn.getAccountForExtension(this, fitnessOptions))         .deleteData(request)         .addOnSuccessListener (unused ->                 Log.i(TAG, "Information deleted successfully!"))         .addOnFailureListener(e ->         Log.w(TAG, "At that place was an error with the deletion request", e));                      

Apps tin can delete data from specific sessions or delete all data. For more than information, run across the API reference for DataDeleteRequest.

Annals for data updates

Your app can read raw sensor data in real fourth dimension past registering with SensorsClient.

For other types of information that are less frequent and are manually counted, your app tin can register to receive updates when these measurements are inserted into the Google Fit database. Examples of these data types include height, weight, and workouts similar weight lifting; for more than details, see the full list of supported data types. To annals for updates, use HistoryClient.registerDataUpdateListener.

The following lawmaking snippet lets an app be notified when the user enters a new value for their weight:

Kotlin

val intent = Intent(this, MyDataUpdateService::class.java) val pendingIntent = PendingIntent.getService(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT)  val request = DataUpdateListenerRegistrationRequest.Architect()     .setDataType(DataType.TYPE_WEIGHT)     .setPendingIntent(pendingIntent)     .build()  Fettle.getHistoryClient(this, GoogleSignIn.getAccountForExtension(this, fitnessOptions))     .registerDataUpdateListener(request)     .addOnSuccessListener {         Log.i(TAG, "DataUpdateListener registered")     }                      

Java

Intent intent = new Intent(this, MyDataUpdateService.class); PendingIntent pendingIntent = PendingIntent.getService(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT)  DataUpdateListenerRegistrationRequest request = new DataUpdateListenerRegistrationRequest.Builder()         .setDataType(DataType.TYPE_WEIGHT)         .setPendingIntent(pendingIntent)         .build();  Fettle.getHistoryClient(this, GoogleSignIn.getAccountForExtension(this, fitnessOptions))         .registerDataUpdateListener(request)         .addOnSuccessListener(unused ->                 Log.i(TAG, "DataUpdateListener registered"));                      

An IntentService tin can exist used to receive notifications of updates:

Kotlin

class MyDataUpdateService : IntentService("MyDataUpdateService") {     override fun onHandleIntent(intent: Intent?) {         val update = DataUpdateNotification.getDataUpdateNotification(intent)         // Prove the time interval over which the data points were collected.         // To extract specific information values, in this case the user's weight,         // use DataReadRequest.         update?.utilize {             val commencement = getUpdateStartTime(TimeUnit.MILLISECONDS)             val terminate = getUpdateEndTime(TimeUnit.MILLISECONDS)              Log.i(TAG, "Data Update start: $start end: $stop DataType: ${dataType.name}")         }     } }                      

Java

public class MyDataUpdateService extends IntentService {      public MyDataUpdateService(String name) {         super("MyDataUpdateService");     }      @Override     protected void onHandleIntent(@Nullable Intent intent) {         if (intent != null) {             DataUpdateNotification update = DataUpdateNotification.getDataUpdateNotification(intent);              // Show the time interval over which the data points             // were collected.             // To extract specific data values, in this case the user'south weight,             // use DataReadRequest.             if (update != null) {                 long start = update.getUpdateStartTime(TimeUnit.MILLISECONDS);                 long end = update.getUpdateEndTime(TimeUnit.MILLISECONDS);             }              Log.i(TAG, "Information Update get-go: $outset end: $cease DataType: ${dataType.name}");         }     } }                      

The IntentService must be declared in your AndroidManifest.xml file.