Work with sessions

Sleep and Activity data types in Health Connect rely on sessions. A session is a time interval during which a user performs an activity. Activity sessions in Health Connect can include anything from running to badminton. Sessions allow users to measure time-based performance. This data records an array of instantaneous samples measured over a period of time, for example a continuous heart rate or location samples during an activity.

The following provides additional information and best practices on how to work with sessions in Health Connect:

  • When to create a session: If you're adding data from a specific workout or activity, or for sleep.
  • When not to create a session: For general measurements like daily step counts.

  • Sessions have a single UID but data within sessions have their own UIDs.

  • Sessions are metadata. They’re specifically useful for instances where the user wants data to be associated with and tracked as part of a session, rather than recorded for a continuous all-day tracker, like a daily step count, for example.

  • Nothing prevents a single application from writing multiple sessions or overlapping them in the same timeframe. Multiple applications can also write multiple sessions into the same timeframe.

Sleep sessions

You can read or write sleep data in Health Connect. It is displayed as a session and can be divided into sleep stages.

Sleep stages include:

  • UNKNOWN : Unspecified or unknown if the user is sleeping.
  • AWAKE : The user is awake (within a sleep cycle, not during the day).
  • SLEEPING : Generic or non-granular sleep description.
  • OUT_OF_BED : The user gets out of bed in the middle of a sleep session.
  • LIGHT : The user is in a light sleep cycle.
  • DEEP : The user is in a deep sleep cycle.
  • REM : The user is in a REM sleep cycle.

These values represent the type of sleep the user was in throughout a time range. Writing sleep stages is optional, but recommended if available.

Writing sleep sessions with or without sleep stages

The Sleep data type in Health Connect has two key parts to it:

  1. The overall session, spanning the entire duration of sleep.
  2. Individual stages during the sleep session such as light sleep or deep sleep.

The following demonstrates how to insert a sleep session, first without stages:

suspend fun writeSleepSession(healthConnectClient: HealthConnectClient) {
    val sleepSession = SleepSession(
        // Optionally add a title
        title = "My sleep",
        // Optionally add some notes
        notes = "Managed to get a good night of sleep",
        startTime = START_TIME,
        startZoneOffset = START_ZONE_OFFSET,
        endTime = END_TIME,
        endZoneOffset = END_TIME_OFFSET
    )
    healthConnectClient.insertRecords(
        listOf(sleepSession)
    )
}

If adding sleep stages, add stages wherever possible to cover the entire period of the overarching sleep session:

suspend fun writeSleepStages(healthConnectClient: HealthConnectClient) {
    // List of sleep stages covering the whole night. In this example, only the
    // first and last is shown, showing alignment to the start and end time of the
    // overarching session.
    val sleepStages = listOf(
        // First sleep stage of the night.
        SleepStage(
            stage = SleepStage.StageType.LIGHT,
            startTime = START_TIME,
            startZoneOffset = START_ZONE_OFFSET,
            endTime = ...,
            endZoneOffset = ...
        ),
        // ... <N further sleep stages for the night>
        // Finally, the last sleep stage of the night:
        SleepStage(
            stage = SleepStage.StageType.SLEEPING,
            startTime = ... ,
            startZoneOffset = ...,
            endTime = END_TIME,
            endZoneOffset = END_ZONE_OFFSET
        )
    )
    healthConnectClient.insertRecords(sleepStages)
}

Reading sleep sessions

The following demonstrates reading sleep sessions between two points in time. For every sleep session returned, you should check whether sleep stage data is also available, as shown:

suspend fun readSleep(healthConnectClient: HealthConnectClient) {
    val sessionsRequest = ReadRecordsRequest(
        recordType = SleepSession::class,
        timeRangeFilter = TimeRangeFilter(START_TIME, END_TIME)
    )
    val sessions = healthConnectClient.readRecords(sessionsRequest)
    sessions.records.forEach { session ->
        // For each sleep session, there may optionally be sleep stage data.
        // Request this using the start and end of the sleep session as bounds.
        val stageRequest = ReadRecordsRequest(
            recordType = SleepStage::class,
            timeRangeFilter = TimeRangeFilter.between(
                session.startTime, session.endTime
            )
        )
        val stages = healthConnectClient.readRecords(stageRequest)

        stages.records.forEach {
            // Process each response
            val stageStartTime = it.startTime
            val stageEndTime = it.endTime
            val stage = it.stage
        }
    }
}

Deleting a session

The following code sample demonstrates how to delete a sleep session.

suspend fun deleteSleepSession(
    healthConnectClient: HealthConnectClient,
    sleepSession: SleepSession
) {
    val timeRangeFilter = TimeRangeFilter
        .between(sleepSession.startTime, sleepSession.endTime)
    healthConnectClient.deleteRecords(SleepSession::class, timeRangeFilter)
    healthConnectClient.deleteRecords(SleepStage::class, timeRangeFilter)
}

Activity sessions

Activity sessions can include anything from running to badminton in Health Connect. The following examples show you how to write and read an activity session.

Writing activity sessions

The following code sample demonstrates how to build an insertion request that includes a session:

suspend fun writeActivitySession(healthConnectClient: HealthConnectClient) {
    healthConnectClient.insertRecords(
        listOf(
            ActivitySession(
                startTime = START_TIME,
                startZoneOffset = START_ZONE_OFFSET,
                endTime = END_TIME,
                endZoneOffset = END_ZONE_OFFSET,
                activityType = ActivitySession.ActivityType.RUNNING,
                title = "My Run"
            ),
            Distance(
                startTime = START_TIME,
                startZoneOffset = START_ZONE_OFFSET,
                endTime = END_TIME,
                endZoneOffset = END_ZONE_OFFSET,
                distanceMeters = 5000.0
            ),
            // ... other records
        )
    )
}

Note how in the previous example, a record is added for Distance, which spans the entire duration of the session, but data can be added with different granularity.

If the app had measured distance regularly during the run, then another approach would be to include many Distance records, each representing the distance covered in a portion of the run.

Reading activity sessions

Here’s an example of how to read activity sessions:

suspend fun readActivitySessions(
    client:HealthConnectClient
): List<ActivitySession> {
    val request = ReadRecordsRequest(
        recordType = ActivitySession::class,
        timeRangeFilter = TimeRangeFilter.between(START_TIME, END_TIME)
    )
    val response = client.readRecords(request)
    return response.records
}