Skip to content

Add get and write HealthData by UUID method #1165

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 9 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 25 additions & 3 deletions packages/health/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,10 @@ The plugin supports:

Note that for Android, the target phone **needs** to have the [Health Connect](https://play.google.com/store/apps/details?id=com.google.android.apps.healthdata&hl=en) app installed (which is currently in beta) and have access to the internet.

### ⚠️ Breaking Changes:

Starting on `12.1.0`, `writeHealthData` and `writeWorkoutData` will return `HealthDataPoint` instead of `bool`. Returns `null` if writing health data failed.

See the tables below for supported health and workout data types.

## Setup
Expand Down Expand Up @@ -192,13 +196,15 @@ Below is a simplified flow of how to use the plugin.
await health.requestAuthorization(types, permissions: permissions);

// write steps and blood glucose
bool success = await health.writeHealthData(10, HealthDataType.STEPS, now, now);
success = await health.writeHealthData(3.1, HealthDataType.BLOOD_GLUCOSE, now, now);
HealthDataPoint? healthPoint = await health.writeHealthData(10, HealthDataType.STEPS, now, now);
healthPoint = await health.writeHealthData(3.1, HealthDataType.BLOOD_GLUCOSE, now, now);

// you can also specify the recording method to store in the metadata (default is RecordingMethod.automatic)
// on iOS only `RecordingMethod.automatic` and `RecordingMethod.manual` are supported
// Android additionally supports `RecordingMethod.active` and `RecordingMethod.unknown`
success &= await health.writeHealthData(10, HealthDataType.STEPS, now, now, recordingMethod: RecordingMethod.manual);
healthPoint = await health.writeHealthData(10, HealthDataType.STEPS, now, now, recordingMethod: RecordingMethod.manual);

bool success = healthPoint != null;

// get the number of steps for today
var midnight = DateTime(now.year, now.month, now.day);
Expand Down Expand Up @@ -311,6 +317,22 @@ List<HealthDataPoint> points = ...;
points = health.removeDuplicates(points);
```

### Fetch single health data by UUID

In order to retrieve a single record, it is required to provide `String uuid` and `HealthDataType type`.

Please see example below:
```dart
HealthDataPoint? healthPoint = await health.getHealthDataByUUID(
uuid: 'd7decd36-a26b-45a0-aa02-91484f8a17ca',
type: HealthDataType.STEPS,
);
```
```
I/FLUTTER_HEALTH( 9161): Success: {uuid=d7decd36-a26b-45a0-aa02-91484f8a17ca, value=12, date_from=1742259061009, date_to=1742259092888, source_id=, source_name=com.google.android.apps.fitness, recording_method=0}
```
> Assuming that the `uuid` and `type` are coming from your database.

## Data Types

The plugin supports the following [`HealthDataType`](https://pub.dev/documentation/health/latest/health/HealthDataType.html).
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import androidx.health.connect.client.records.metadata.Metadata
import androidx.health.connect.client.request.AggregateGroupByDurationRequest
import androidx.health.connect.client.request.AggregateRequest
import androidx.health.connect.client.request.ReadRecordsRequest
import androidx.health.connect.client.response.InsertRecordsResponse
import androidx.health.connect.client.time.TimeRangeFilter
import androidx.health.connect.client.units.*
import io.flutter.embedding.engine.plugins.FlutterPlugin
Expand Down Expand Up @@ -157,6 +158,7 @@ class HealthPlugin(private var channel: MethodChannel? = null) :
"requestAuthorization" -> requestAuthorization(call, result)
"revokePermissions" -> revokePermissions(call, result)
"getData" -> getData(call, result)
"getDataByUUID" -> getDataByUUID(call, result)
"getIntervalData" -> getIntervalData(call, result)
"writeData" -> writeData(call, result)
"delete" -> deleteData(call, result)
Expand Down Expand Up @@ -905,6 +907,189 @@ class HealthPlugin(private var channel: MethodChannel? = null) :
}
}

private fun getDataByUUID(call: MethodCall, result: Result) {
val arguments = call.arguments as? HashMap<*, *>
val dataType = (arguments?.get("dataTypeKey") as? String)!!
val uuid = (arguments?.get("uuid") as? String)!!
var healthPoint = mapOf<String, Any?>()

if (!mapToType.containsKey(dataType)) {
Log.w("FLUTTER_HEALTH::ERROR", "Datatype $dataType not found in HC")
result.success(null)
return
}

val classType = mapToType[dataType]!!

scope.launch {
try {

Log.i("FLUTTER_HEALTH", "Getting $uuid with $classType")

// Execute the request
val response = healthConnectClient.readRecord(classType, uuid)

// Find the record with the matching UUID
val matchingRecord = response.record

if (matchingRecord != null) {
// Workout needs distance and total calories burned too
if (dataType == WORKOUT) {
val record = matchingRecord as ExerciseSessionRecord
val distanceRequest =
healthConnectClient.readRecords(
ReadRecordsRequest(
recordType =
DistanceRecord::class,
timeRangeFilter =
TimeRangeFilter.between(
record.startTime,
record.endTime,
),
),
)
var totalDistance = 0.0
for (distanceRec in distanceRequest.records) {
totalDistance +=
distanceRec.distance
.inMeters
}

val energyBurnedRequest =
healthConnectClient.readRecords(
ReadRecordsRequest(
recordType =
TotalCaloriesBurnedRecord::class,
timeRangeFilter =
TimeRangeFilter.between(
record.startTime,
record.endTime,
),
),
)
var totalEnergyBurned = 0.0
for (energyBurnedRec in
energyBurnedRequest.records) {
totalEnergyBurned +=
energyBurnedRec.energy
.inKilocalories
}

val stepRequest =
healthConnectClient.readRecords(
ReadRecordsRequest(
recordType =
StepsRecord::class,
timeRangeFilter =
TimeRangeFilter.between(
record.startTime,
record.endTime
),
),
)
var totalSteps = 0.0
for (stepRec in stepRequest.records) {
totalSteps += stepRec.count
}

// val metadata = (rec as Record).metadata
// Add final datapoint
healthPoint = mapOf<String, Any?>(
"uuid" to record.metadata.id,
"workoutActivityType" to
(workoutTypeMap
.filterValues {
it ==
record.exerciseType
}
.keys
.firstOrNull()
?: "OTHER"),
"totalDistance" to
if (totalDistance ==
0.0
)
null
else
totalDistance,
"totalDistanceUnit" to
"METER",
"totalEnergyBurned" to
if (totalEnergyBurned ==
0.0
)
null
else
totalEnergyBurned,
"totalEnergyBurnedUnit" to
"KILOCALORIE",
"totalSteps" to
if (totalSteps ==
0.0
)
null
else
totalSteps,
"totalStepsUnit" to
"COUNT",
"unit" to "MINUTES",
"date_from" to
matchingRecord.startTime
.toEpochMilli(),
"date_to" to
matchingRecord.endTime.toEpochMilli(),
"source_id" to "",
"source_name" to
record.metadata
.dataOrigin
.packageName,
)
// Filter sleep stages for requested stage
} else if (classType == SleepSessionRecord::class) {
if (matchingRecord is SleepSessionRecord) {
if (dataType == SLEEP_SESSION) {
healthPoint = convertRecord(
matchingRecord,
dataType
)[0]
} else {
for (recStage in matchingRecord.stages) {
if (dataType ==
mapSleepStageToType[
recStage.stage]
) {
healthPoint = convertRecordStage(
recStage,
dataType,
matchingRecord.metadata
)[0]
}
}
}
}
} else {
healthPoint = convertRecord(matchingRecord, dataType)[0]
}

Log.i(
"FLUTTER_HEALTH",
"Success: $healthPoint"
)

Handler(context!!.mainLooper).run { result.success(healthPoint) }
} else {
Log.e("FLUTTER_HEALTH::ERROR", "Record not found for UUID: $uuid")
result.success(null)
}
} catch (e: Exception) {
Log.e("FLUTTER_HEALTH::ERROR", "Error fetching record with UUID: $uuid")
Log.e("FLUTTER_HEALTH::ERROR", e.message ?: "unknown error")
Log.e("FLUTTER_HEALTH::ERROR", e.stackTraceToString())
result.success(null)
}
}
}

private fun convertRecordStage(
stage: SleepSessionRecord.Stage,
dataType: String,
Expand Down Expand Up @@ -2224,8 +2409,23 @@ class HealthPlugin(private var channel: MethodChannel? = null) :
}
scope.launch {
try {
healthConnectClient.insertRecords(listOf(record))
result.success(true)
// Insert records into Health Connect
val insertResponse: InsertRecordsResponse = healthConnectClient.insertRecords(listOf(record))
// Log.i("FLUTTER_HEALTH::DEBUG", "Inserted records: $insertResponse")

// Extract UUID from the first inserted record
val insertedUUID = insertResponse.recordIdsList.firstOrNull() ?: ""

if (insertedUUID.isEmpty()) {
Log.e("FLUTTER_HEALTH::ERROR", "UUID is empty! No records were inserted.")
}

Log.i(
"FLUTTER_HEALTH::SUCCESS",
"[Health Connect] Workout $insertedUUID was successfully added!"
)

result.success(insertedUUID)
} catch (e: Exception) {
result.success(false)
}
Expand Down Expand Up @@ -2302,22 +2502,32 @@ class HealthPlugin(private var channel: MethodChannel? = null) :
),
)
}
healthConnectClient.insertRecords(
list,
)
result.success(true)

// Insert records into Health Connect
val insertResponse: InsertRecordsResponse = healthConnectClient.insertRecords(list)
// Log.i("FLUTTER_HEALTH::DEBUG", "Inserted records: $insertResponse")

// Extract UUID from the first inserted record
val insertedUUID = insertResponse.recordIdsList.firstOrNull() ?: ""

if (insertedUUID.isEmpty()) {
Log.e("FLUTTER_HEALTH::ERROR", "UUID is empty! No records were inserted.")
}

Log.i(
"FLUTTER_HEALTH::SUCCESS",
"[Health Connect] Workout was successfully added!"
"[Health Connect] Workout $insertedUUID was successfully added!"
)

result.success(insertedUUID)
} catch (e: Exception) {
Log.w(
"FLUTTER_HEALTH::ERROR",
"[Health Connect] There was an error adding the workout",
)
Log.w("FLUTTER_HEALTH::ERROR", e.message ?: "unknown error")
Log.w("FLUTTER_HEALTH::ERROR", e.stackTrace.toString())
result.success(false)
result.success("")
}
}
}
Expand Down
Loading