Health Connect update information in my app, only if I launch Google Fit app

118 Views Asked by At

I need to show the user the steps for the day. I decided to use Google Health Connect for this purpose. When I query StepsRecords, I get a list of recent records. But they are not up to date until I launch Google Fit.

Maybe I need to fill out a google form? I still haven't figured out if this is mandatory or not?

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        val healthConnectClient = HealthConnectClient.getOrCreate(this)
        val someFlow = MutableStateFlow(0L)
        lifecycleScope.launch {
            someFlow.emit(
                readStepsByTimeRange(
                    healthConnectClient,
                    Instant.now().minus(Duration.ofDays(1)),
                    Instant.now()
                )
            )
        }
        setContent {
            Text(text = someFlow.collectAsState().value.toString())
        }
    }

    suspend fun readStepsByTimeRange(
        healthConnectClient: HealthConnectClient,
        startTime: Instant,
        endTime: Instant
    ): Long {
        return try {
            Log.d("TAG", "readStepsByTimeRange: begin")
            val response =
                healthConnectClient.readRecords(
                    ReadRecordsRequest(
                        recordType = StepsRecord::class,
                        timeRangeFilter = TimeRangeFilter.between(startTime, endTime)
                    )
                )

            Log.d("TAG", "readStepsByTimeRange: response $response")

            response.records.map {
                Triple(it.startTime, it.endTime, it.count)
            }.onEach {
                Log.d("TAG", "readStepsByTimeRange: $it")
            }
            response.records.sumOf { it.count }
        } catch (e: Exception) {
            Log.d("TAG", "readStepsByTimeRange: $e")
            return 0L
        }
    }
}
0

There are 0 best solutions below