android / health-samples

Apache License 2.0
270 stars 150 forks source link

Google Fit Missing One Step When Crossing Two Dates #282

Open wtlin3 opened 3 months ago

wtlin3 commented 3 months ago

I am syncing Google Fit with Health Connect and retrieving daily step counts for the current month. However, I am encountering an issue where steps crossing two dates are missing one step.

Example:

As a result, one step is missing. :smiling_face_with_tear: Does anyone know how to resolve this issue? Thanks!

01

View daily step counts for 7/28 and 7/29

Note: However, when switching tabs in Google Fit, the step count for 7/28 sometimes shows 2 steps and other times shows 1 step.

7/28 7/29

View step counts for the entire month

View step counts for the entire month

View step counts for this week

View step counts for this week
breanatate commented 3 months ago

Hi, thanks for reaching out.

What are you seeing when reading the steps from Health Connect (alternatively, are you also seeing a discrepancy in what Google Fit writes to Health Connect?)? The information provided here appears to be specific to the Google Fit app, rather than the Health Connect API.

wtlin3 commented 3 months ago

@breanatate Hi Here is a snippet of code that retrieves Google Fit step count data using HealthConnect.

suspend fun aggregateSteps(): HealthInfo {
    // Create a list to store daily step count data
    val stepsDataPerDay = mutableListOf<StepCountList>()
    // Get the current date
    val now = LocalDate.now()
    // Set the start time to the first day of the month at midnight
    val startTime = now.withDayOfMonth(1).atStartOfDay()
    // Get the current year and month, and format them as "yyyymm"
    val yearMonth = "${now.year}${now.monthValue.toString().padStart(2, '0')}"

    // Get each day of the current month
    for (i in 0 until now.lengthOfMonth()) {
        try {
            // Create an AggregateRequest to get daily step counts
            val response = healthConnectClient.aggregate(
                AggregateRequest(
                    metrics = setOf(StepsRecord.COUNT_TOTAL),
                    timeRangeFilter = TimeRangeFilter.between(
                        startTime.plusDays(i.toLong()),
                        startTime.plusDays(i.toLong() + 1)
                    )
                )
            )

            // If there is no data in the specified time range, the result may be null, here using 0 as the default value
            val stepCount = response[StepsRecord.COUNT_TOTAL] ?: 0
            // Format the date
            val date = startTime.plusDays(i.toLong()).format(DATE_FORMAT)

            stepsDataPerDay.add(StepCountList(date.format(DATE_FORMAT), stepCount.toInt()))
            Log.d(TAG, "$date : $stepCount")

        } catch (e: Exception) {
            // Run error handling here
        }
    }
}

Debug

7:28 7:29 Screenshot_20240807-150520