1 /** 2 * Copyright (C) 2024 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except 5 * in compliance with the License. You may obtain a copy of the License at 6 * 7 * ``` 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * ``` 10 * 11 * Unless required by applicable law or agreed to in writing, software distributed under the License 12 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 13 * or implied. See the License for the specific language governing permissions and limitations under 14 * the License. 15 */ 16 package com.android.healthconnect.testapps.toolbox.ui 17 18 import android.health.connect.HealthConnectManager 19 import android.health.connect.ReadRecordsRequestUsingFilters 20 import android.health.connect.TimeInstantRangeFilter 21 import android.health.connect.datatypes.Record 22 import android.health.connect.datatypes.StepsRecord 23 import android.os.Bundle 24 import android.view.View 25 import android.widget.Button 26 import androidx.fragment.app.Fragment 27 import androidx.lifecycle.lifecycleScope 28 import com.android.healthconnect.testapps.toolbox.R 29 import com.android.healthconnect.testapps.toolbox.utils.GeneralUtils.Companion.readRecords 30 import com.android.healthconnect.testapps.toolbox.utils.GeneralUtils.Companion.requireSystemService 31 import com.android.healthconnect.testapps.toolbox.utils.GeneralUtils.Companion.showMessageDialog 32 import com.android.healthconnect.testapps.toolbox.utils.asString 33 import kotlinx.coroutines.launch 34 import java.time.Instant 35 36 class ReadDataInForegroundFragment : Fragment(R.layout.fragment_read_data_in_foreground) { 37 <lambda>null38 private val healthConnectManager: HealthConnectManager by lazy { 39 requireContext().requireSystemService() 40 } 41 onViewCreatednull42 override fun onViewCreated(view: View, savedInstanceState: Bundle?) { 43 super.onViewCreated(view, savedInstanceState) 44 45 view.requireViewById<Button>(R.id.read_steps_button).setOnClickListener { 46 executeAndShowMessage { readAllRecords<StepsRecord>() } 47 } 48 } 49 executeAndShowMessagenull50 private fun executeAndShowMessage(block: suspend () -> String) { 51 lifecycleScope.launch { 52 val result = 53 try { 54 block() 55 } catch (e: Exception) { 56 e.toString() 57 } 58 59 requireContext().showMessageDialog(result) 60 } 61 } 62 readAllRecordsnull63 private suspend inline fun <reified T : Record> readAllRecords(): String = 64 readRecords( 65 manager = healthConnectManager, 66 request = ReadRecordsRequestUsingFilters.Builder(T::class.java) 67 .setTimeRangeFilter( 68 TimeInstantRangeFilter.Builder() 69 .setStartTime(Instant.EPOCH) 70 .setEndTime(Instant.now()) 71 .build() 72 ) 73 .build(), 74 ).joinToString(separator = "\n", transform = Record::asString) 75 } 76