The following example shows you how to read raw data as part of the common workflow.
Read data
Health Connect allows apps to read data from the datastore when the app is in the foreground and background:
Foreground reads: You can normally read data from Health Connect when your app is in the foreground. In these cases, you may consider using a foreground service to run this operation in case the user or system places your app in the background during a read operation.
Background reads: By requesting an extra permission from the user, you can read data after the user or system places your app in the background. See the complete background read example.
The Steps data type in Health Connect captures the number of steps a user has taken between readings. Step counts represent a common measurement across health, fitness, and wellness platforms. Health Connect makes it simple to read and write step count data.
To read records, create a ReadRecordsRequest
and supply
it when you call readRecords
.
The following example shows how to read step count data for a user within a
certain time. For an extended example with SensorManager
,
see the step count
data guide.
suspend fun readStepsByTimeRange(
healthConnectClient: HealthConnectClient,
startTime: Instant,
endTime: Instant
) {
try {
val response = healthConnectClient.readRecords(
ReadRecordsRequest(
StepsRecord::class,
timeRangeFilter = TimeRangeFilter.between(startTime, endTime)
)
)
for (stepRecord in response.records) {
// Process each step record
}
} catch (e: Exception) {
// Run error handling here
}
}
Background read example
To read data in the background, declare the following permission in your manifest file:
<application>
<uses-permission android:name="android.permission.health.READ_HEALTH_DATA_IN_BACKGROUND" />
...
</application>
The following example shows how to read step count data in the background for a
user within a certain time by using WorkManager
:
class ScheduleWorker(private val appContext: Context, workerParams: WorkerParameters):
CoroutineWorker(appContext, workerParams) {
override suspend fun doWork(): Result {
// Read data and process it.
...
// Return success indicating successful data retrieval
return Result.success()
}
}
if (healthConnectClient
.features
.getFeatureStatus(
HealthConnectFeatures.FEATURE_READ_HEALTH_DATA_IN_BACKGROUND
) == HealthConnectFeatures.FEATURE_STATUS_AVAILABLE) {
// Check if necessary permission is granted
val grantedPermissions = healthConnectClient.permissionController.getGrantedPermissions()
if (PERMISSION_READ_HEALTH_DATA_IN_BACKGROUND !in grantedPermissions) {
// Perform read in foreground
...
} else {
// Schedule the periodic work request in background
val periodicWorkRequest = PeriodicWorkRequestBuilder<ScheduleWorker>(1, TimeUnit.HOURS)
.build()
WorkManager.getInstance(context).enqueueUniquePeriodicWork(
"read_health_connect",
ExistingPeriodicWorkPolicy.KEEP,
periodicWorkRequest
)
}
} else {
// Background reading is not available, perform read in foreground
...
}
Read previously written data
If an app has written records to Health Connect before, it is possible for that app to read them back without requiring a Read permission to those specific records. This is applicable to scenarios in which the app needs to resync with Health Connect after the user has reinstalled it.
To read data in this scenario, you need to indicate the package name as a
DataOrigin
object in the dataOriginFilter
parameter of your
ReadRecordsRequest
.
The following example shows how to indicate a package name when reading Steps records:
try {
val response = healthConnectClient.readRecords(
ReadRecordsRequest(
recordType = StepsRecord::class,
timeRangeFilter = TimeRangeFilter.between(startTime, endTime),
dataOriginFilter = setOf(DataOrigin("com.my.package.name"))
)
)
for (record in response.records) {
// Process each record
}
} catch (e: Exception) {
// Run error handling here
}
Read restrictions
By default, your app can read data up to 30 days with any permissions granted.
With the PERMISSION_READ_HEALTH_DATA_HISTORY
permission, your app can
read data older than 30 days.
30-day restriction
Health Connect can read data for up to 30 days prior to when any permission was first granted.
However, if a user deletes your app, the permission history is lost. If the user reinstalls your app and grants permission again, your app can read data from Health Connect up to 30 days prior to that new date.
30-day example
If a user first granted read permission to your application on March 30, 2023, the earliest data your app could read back would be from February 28, 2023 onwards.
The user then deletes your app on May 10, 2023. The user decides to reinstall it on May 15, 2023 and grant read permission. The earliest date your app can now read data from is April 15, 2023.
Read data older than 30 days
If you would like to read data older than 30 days, you must use the
PERMISSION_READ_HEALTH_DATA_HISTORY
permission. Without this permission,
an attempt to read a single record older than 30 days results in an error.
You also can't read any data older than 30 days using one of the time range
requests.