Skip to content

Offline gym log for Android. No account, no ads, no internet.

Health Connect: save workouts, heart rate, weigh-ins and steps

InlitXa151f56c98ea
diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml
index 9dccee2..e57a822 100644
--- a/android/app/src/main/AndroidManifest.xml
+++ b/android/app/src/main/AndroidManifest.xml
@@ -23,6 +23,8 @@
<uses-permission android:name="android.permission.health.READ_FLOORS_CLIMBED"/>
<uses-permission android:name="android.permission.health.READ_ELEVATION_GAINED"/>
<uses-permission android:name="android.permission.health.READ_ACTIVE_CALORIES_BURNED"/>
+ <uses-permission android:name="android.permission.health.READ_WEIGHT"/>
+ <uses-permission android:name="android.permission.health.WRITE_EXERCISE"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" tools:node="remove"/>
<uses-feature android:name="android.hardware.type.watch" android:required="false"/>
diff --git a/android/app/src/main/kotlin/com/gymmane/app/HealthBridge.kt b/android/app/src/main/kotlin/com/gymmane/app/HealthBridge.kt
index 7a87877..f0cd897 100644
--- a/android/app/src/main/kotlin/com/gymmane/app/HealthBridge.kt
+++ b/android/app/src/main/kotlin/com/gymmane/app/HealthBridge.kt
@@ -9,6 +9,8 @@ import android.health.connect.AggregateRecordsResponse
import android.health.connect.HealthConnectException
import android.health.connect.HealthConnectManager
import android.health.connect.HealthPermissions
+import android.health.connect.InsertRecordsResponse
+import android.health.connect.RecordIdFilter
import android.health.connect.LocalTimeRangeFilter
import android.health.connect.ReadRecordsRequestUsingFilters
import android.health.connect.ReadRecordsResponse
@@ -19,15 +21,19 @@ import android.health.connect.datatypes.BloodPressureRecord
import android.health.connect.datatypes.BodyTemperatureRecord
import android.health.connect.datatypes.DistanceRecord
import android.health.connect.datatypes.ElevationGainedRecord
+import android.health.connect.datatypes.ExerciseSessionRecord
+import android.health.connect.datatypes.ExerciseSessionType
import android.health.connect.datatypes.FloorsClimbedRecord
import android.health.connect.datatypes.HeartRateRecord
import android.health.connect.datatypes.HeartRateVariabilityRmssdRecord
+import android.health.connect.datatypes.Metadata
import android.health.connect.datatypes.OxygenSaturationRecord
import android.health.connect.datatypes.Record
import android.health.connect.datatypes.RespiratoryRateRecord
import android.health.connect.datatypes.RestingHeartRateRecord
import android.health.connect.datatypes.SleepSessionRecord
import android.health.connect.datatypes.StepsRecord
+import android.health.connect.datatypes.WeightRecord
import android.os.Build
import android.os.OutcomeReceiver
import androidx.annotation.RequiresApi
@@ -62,6 +68,44 @@ object HealthBridge {
"floors" to "android.permission.health.READ_FLOORS_CLIMBED",
"elevation" to "android.permission.health.READ_ELEVATION_GAINED",
"activeKcal" to "android.permission.health.READ_ACTIVE_CALORIES_BURNED",
+ "workoutHr" to "android.permission.health.READ_HEART_RATE",
+ "weight" to "android.permission.health.READ_WEIGHT",
+ "writeWorkouts" to "android.permission.health.WRITE_EXERCISE",
+ "steps" to "android.permission.health.READ_STEPS",
+ )
+
+ private val sessionTypes = mapOf(
+ "strength" to ExerciseSessionType.EXERCISE_SESSION_TYPE_STRENGTH_TRAINING,
+ "running" to ExerciseSessionType.EXERCISE_SESSION_TYPE_RUNNING,
+ "treadmill" to ExerciseSessionType.EXERCISE_SESSION_TYPE_RUNNING_TREADMILL,
+ "walking" to ExerciseSessionType.EXERCISE_SESSION_TYPE_WALKING,
+ "biking" to ExerciseSessionType.EXERCISE_SESSION_TYPE_BIKING,
+ "stationaryBike" to ExerciseSessionType.EXERCISE_SESSION_TYPE_BIKING_STATIONARY,
+ "rowing" to ExerciseSessionType.EXERCISE_SESSION_TYPE_ROWING_MACHINE,
+ "elliptical" to ExerciseSessionType.EXERCISE_SESSION_TYPE_ELLIPTICAL,
+ "stairs" to ExerciseSessionType.EXERCISE_SESSION_TYPE_STAIR_CLIMBING_MACHINE,
+ "swimming" to ExerciseSessionType.EXERCISE_SESSION_TYPE_SWIMMING_POOL,
+ "hiit" to ExerciseSessionType.EXERCISE_SESSION_TYPE_HIGH_INTENSITY_INTERVAL_TRAINING,
+ "calisthenics" to ExerciseSessionType.EXERCISE_SESSION_TYPE_CALISTHENICS,
+ "yoga" to ExerciseSessionType.EXERCISE_SESSION_TYPE_YOGA,
+ "stretching" to ExerciseSessionType.EXERCISE_SESSION_TYPE_STRETCHING,
+ "football" to ExerciseSessionType.EXERCISE_SESSION_TYPE_SOCCER,
+ "basketball" to ExerciseSessionType.EXERCISE_SESSION_TYPE_BASKETBALL,
+ "volleyball" to ExerciseSessionType.EXERCISE_SESSION_TYPE_VOLLEYBALL,
+ "tennis" to ExerciseSessionType.EXERCISE_SESSION_TYPE_TENNIS,
+ "padel" to ExerciseSessionType.EXERCISE_SESSION_TYPE_RACQUETBALL,
+ "badminton" to ExerciseSessionType.EXERCISE_SESSION_TYPE_BADMINTON,
+ "squash" to ExerciseSessionType.EXERCISE_SESSION_TYPE_SQUASH,
+ "table-tennis" to ExerciseSessionType.EXERCISE_SESSION_TYPE_TABLE_TENNIS,
+ "handball" to ExerciseSessionType.EXERCISE_SESSION_TYPE_HANDBALL,
+ "rugby" to ExerciseSessionType.EXERCISE_SESSION_TYPE_RUGBY,
+ "boxing" to ExerciseSessionType.EXERCISE_SESSION_TYPE_BOXING,
+ "martial-arts" to ExerciseSessionType.EXERCISE_SESSION_TYPE_MARTIAL_ARTS,
+ "climbing" to ExerciseSessionType.EXERCISE_SESSION_TYPE_ROCK_CLIMBING,
+ "skiing" to ExerciseSessionType.EXERCISE_SESSION_TYPE_SKIING,
+ "surfing" to ExerciseSessionType.EXERCISE_SESSION_TYPE_SURFING,
+ "dance" to ExerciseSessionType.EXERCISE_SESSION_TYPE_DANCING,
+ "golf" to ExerciseSessionType.EXERCISE_SESSION_TYPE_GOLF,
)
fun attach(activity: Activity, channel: MethodChannel) {
@@ -89,6 +133,18 @@ object HealthBridge {
call.argument<Number>("to")?.toLong() ?: 0L,
result,
)
+ "writeWorkout" -> writeWorkout(
+ activity,
+ call.argument<String>("id").orEmpty(),
+ call.argument<Number>("start")?.toLong() ?: 0L,
+ call.argument<Number>("end")?.toLong() ?: 0L,
+ call.argument<String>("type").orEmpty(),
+ call.argument<String>("title").orEmpty(),
+ call.argument<String>("notes").orEmpty(),
+ call.argument<Boolean>("manual") ?: false,
+ result,
+ )
+ "deleteWorkout" -> deleteWorkout(activity, call.argument<String>("id").orEmpty(), result)
else -> result.notImplemented()
}
}
@@ -137,6 +193,77 @@ object HealthBridge {
activity.requestPermissions(wanted.toTypedArray(), REQUEST_CODE)
}
+ @RequiresApi(Build.VERSION_CODES.UPSIDE_DOWN_CAKE)
+ private fun canWrite(activity: Activity): HealthConnectManager? {
+ val manager = activity.getSystemService(HealthConnectManager::class.java) ?: return null
+ val granted = activity.checkSelfPermission(metrics.getValue("writeWorkouts")) == PackageManager.PERMISSION_GRANTED
+ return if (granted) manager else null
+ }
+
+ @RequiresApi(Build.VERSION_CODES.UPSIDE_DOWN_CAKE)
+ private fun writeWorkout(
+ activity: Activity,
+ id: String,
+ start: Long,
+ end: Long,
+ type: String,
+ title: String,
+ notes: String,
+ manual: Boolean,
+ result: MethodChannel.Result,
+ ) {
+ val manager = canWrite(activity)
+ if (manager == null || id.isEmpty() || end <= start) return result.success(false)
+ try {
+ val metadata = Metadata.Builder()
+ .setClientRecordId(id)
+ .setClientRecordVersion(System.currentTimeMillis())
+ .setRecordingMethod(
+ if (manual) Metadata.RECORDING_METHOD_MANUAL_ENTRY else Metadata.RECORDING_METHOD_ACTIVELY_RECORDED,
+ )
+ .build()
+ val record = ExerciseSessionRecord.Builder(
+ metadata,
+ Instant.ofEpochMilli(start),
+ Instant.ofEpochMilli(end),
+ sessionTypes[type] ?: ExerciseSessionType.EXERCISE_SESSION_TYPE_OTHER_WORKOUT,
+ ).apply {
+ if (title.isNotEmpty()) setTitle(title)
+ if (notes.isNotEmpty()) setNotes(notes)
+ }.build()
+ manager.insertRecords(
+ listOf(record),
+ activity.mainExecutor,
+ object : OutcomeReceiver<InsertRecordsResponse, HealthConnectException> {
+ override fun onResult(response: InsertRecordsResponse) = result.success(true)
+
+ override fun onError(error: HealthConnectException) = result.success(false)
+ },
+ )
+ } catch (e: Exception) {
+ result.success(false)
+ }
+ }
+
+ @RequiresApi(Build.VERSION_CODES.UPSIDE_DOWN_CAKE)
+ private fun deleteWorkout(activity: Activity, id: String, result: MethodChannel.Result) {
+ val manager = canWrite(activity)
+ if (manager == null || id.isEmpty()) return result.success(false)
+ try {
+ manager.deleteRecords(
+ listOf(RecordIdFilter.fromClientRecordId(ExerciseSessionRecord::class.java, id)),
+ activity.mainExecutor,
+ object : OutcomeReceiver<Void, HealthConnectException> {
+ override fun onResult(response: Void?) = result.success(true)
+
+ override fun onError(error: HealthConnectException) = result.success(false)
+ },
+ )
+ } catch (e: Exception) {
+ result.success(false)
+ }
+ }
+
@RequiresApi(Build.VERSION_CODES.UPSIDE_DOWN_CAKE)
private fun readMetric(activity: Activity, key: String, from: Long, to: Long, result: MethodChannel.Result) {
val manager = activity.getSystemService(HealthConnectManager::class.java)
@@ -173,6 +300,12 @@ object HealthBridge {
"temperature" -> reader.records(BodyTemperatureRecord::class.java) {
listOf(it.time.toEpochMilli().toDouble(), it.temperature.inCelsius)
}
+ "workoutHr" -> reader.flat(HeartRateRecord::class.java) { record ->
+ record.samples.map { listOf(it.time.toEpochMilli().toDouble(), it.beatsPerMinute.toDouble()) }
+ }
+ "weight" -> reader.records(WeightRecord::class.java) {
+ listOf(it.time.toEpochMilli().toDouble(), it.weight.inGrams / 1000.0)
+ }
"sleep" -> reader.records(SleepSessionRecord::class.java) {
val start = it.startTime.toEpochMilli()
val end = it.endTime.toEpochMilli()
@@ -222,7 +355,9 @@ object HealthBridge {
}
}
- fun <T : Record> records(type: Class<T>, row: (T) -> List<Double>) {
+ fun <T : Record> records(type: Class<T>, row: (T) -> List<Double>) = flat(type) { listOf(row(it)) }
+
+ fun <T : Record> flat(type: Class<T>, rowsOf: (T) -> List<List<Double>>) {
val filter = TimeInstantRangeFilter.Builder()
.setStartTime(Instant.ofEpochMilli(from))
.setEndTime(Instant.ofEpochMilli(to))
@@ -239,7 +374,7 @@ object HealthBridge {
activity.mainExecutor,
object : OutcomeReceiver<ReadRecordsResponse<T>, HealthConnectException> {
override fun onResult(response: ReadRecordsResponse<T>) {
- response.records.forEach { rows.add(row(it)) }
+ response.records.forEach { rows.addAll(rowsOf(it)) }
val next = response.nextPageToken
if (next != -1L && rows.size < MAX_ROWS) page(next) else result.success(rows)
}
diff --git a/lib/services/health_metrics.dart b/lib/services/health_metrics.dart
index b07ec70..0e29e20 100644
--- a/lib/services/health_metrics.dart
+++ b/lib/services/health_metrics.dart
@@ -65,11 +65,75 @@ class HealthMetrics {
}
}
- static Future<List<List<double>>?> read(HealthMetric metric, DateTime from, DateTime to) async {
+ static Future<Set<String>> grantedKeys() async {
+ if (!Platform.isAndroid) return {};
+ try {
+ return {...?await _channel.invokeListMethod<String>('metricsGranted')};
+ } on PlatformException {
+ return {};
+ } on MissingPluginException {
+ return {};
+ }
+ }
+
+ static Future<bool> requestKeys(List<String> keys) async {
+ if (!Platform.isAndroid) return false;
+ try {
+ return await _channel.invokeMethod<bool>('requestMetrics', {'metrics': keys}) ?? false;
+ } on PlatformException {
+ return false;
+ } on MissingPluginException {
+ return false;
+ }
+ }
+
+ static Future<bool> writeWorkout({
+ required String id,
+ required DateTime start,
+ required DateTime end,
+ required String type,
+ required String title,
+ String notes = '',
+ bool manual = false,
+ }) async {
+ if (!Platform.isAndroid) return false;
+ try {
+ return await _channel.invokeMethod<bool>('writeWorkout', {
+ 'id': id,
+ 'start': start.millisecondsSinceEpoch,
+ 'end': end.millisecondsSinceEpoch,
+ 'type': type,
+ 'title': title,
+ 'notes': notes,
+ 'manual': manual,
+ }) ??
+ false;
+ } on PlatformException {
+ return false;
+ } on MissingPluginException {
+ return false;
+ }
+ }
+
+ static Future<bool> deleteWorkout(String id) async {
+ if (!Platform.isAndroid) return false;
+ try {
+ return await _channel.invokeMethod<bool>('deleteWorkout', {'id': id}) ?? false;
+ } on PlatformException {
+ return false;
+ } on MissingPluginException {
+ return false;
+ }
+ }
+
+ static Future<List<List<double>>?> read(HealthMetric metric, DateTime from, DateTime to) =>
+ readKey(metric.name, from, to);
+
+ static Future<List<List<double>>?> readKey(String key, DateTime from, DateTime to) async {
if (!Platform.isAndroid) return null;
try {
final rows = await _channel.invokeListMethod<Object?>('readMetric', {
- 'metric': metric.name,
+ 'metric': key,
'from': from.millisecondsSinceEpoch,
'to': to.millisecondsSinceEpoch,
});
diff --git a/lib/state/health_state.dart b/lib/state/health_state.dart
index dba815a..58c1274 100644
--- a/lib/state/health_state.dart
+++ b/lib/state/health_state.dart
@@ -6,8 +6,159 @@ mixin HealthState on FitCore {
final Set<HealthMetric> healthShown = {};
final List<HealthMetric> healthPinned = [];
Set<HealthMetric> healthGranted = {};
+ final Set<HealthMetric> healthFailed = {};
final Map<HealthMetric, Map<String, List<double>>> healthByDay = {};
Future<void>? _healthRunning;
+ bool hcWeights = false;
+ bool hcHeart = false;
+ bool hcWrite = false;
+ final Set<int> hcSeenWeights = {};
+
+ Future<bool> setHcWrite(bool on) async {
+ if (on && !(await HealthMetrics.grantedKeys()).contains('writeWorkouts')) {
+ await HealthMetrics.requestKeys(['writeWorkouts']);
+ if (!(await HealthMetrics.grantedKeys()).contains('writeWorkouts')) {
+ notifyListeners();
+ return false;
+ }
+ }
+ hcWrite = on;
+ _persist();
+ notifyListeners();
+ if (on) {
+ final since = DateTime.now().subtract(const Duration(days: 30));
+ for (final s in sessions.where((s) => s.date.isAfter(since)).toList()) {
+ await _sendWorkout(s);
+ }
+ }
+ return true;
+ }
+
+ static String healthWorkoutId(LoggedSession s) => 'gymmane-${s.date.millisecondsSinceEpoch}';
+
+ String healthWorkoutType(LoggedSession s) {
+ if (s.exercises.isEmpty || s.exercises.any((e) => countsForMuscles(e.id))) return 'strength';
+ final id = s.exercises.first.id.toLowerCase();
+ if (kSportIcons.containsKey(id)) return id;
+ bool has(List<String> words) => words.any(id.contains);
+ if (has(['treadmill'])) return 'treadmill';
+ if (has(['run', 'jog', 'sprint'])) return 'running';
+ if (has(['walk', 'hike'])) return 'walking';
+ if (has(['stationary', 'spin', 'assault', 'air-bike', 'airbike'])) return 'stationaryBike';
+ if (has(['bike', 'cycl'])) return 'biking';
+ if (has(['row'])) return 'rowing';
+ if (has(['elliptical'])) return 'elliptical';
+ if (has(['stair', 'step-mill', 'stepmill'])) return 'stairs';
+ if (has(['swim'])) return 'swimming';
+ return 'other';
+ }
+
+ String healthWorkoutNotes(LoggedSession s) {
+ final text = s.exercises.map((e) => t.catalogName(e.id, e.name)).join(' · ');
+ return text.length > 500 ? '${text.substring(0, 497)}…' : text;
+ }
+
+ Future<bool> _sendWorkout(LoggedSession s) async {
+ if (!hcWrite || s.durationSec <= 0) return false;
+ final title = s.name?.trim().isNotEmpty == true ? s.name!.trim() : t.healthWorkoutTitle;
+ return HealthMetrics.writeWorkout(
+ id: healthWorkoutId(s),
+ start: s.day,
+ end: s.date,
+ type: healthWorkoutType(s),
+ title: title,
+ notes: healthWorkoutNotes(s),
+ );
+ }
+
+ @override
+ void healthSave(LoggedSession s) {
+ if (hcWrite) _sendWorkout(s);
+ }
+
+ @override
+ void healthForget(LoggedSession s) {
+ if (hcWrite) HealthMetrics.deleteWorkout(healthWorkoutId(s));
+ }
+
+ Future<bool> setHcWeights(bool on) async {
+ if (on && !(await HealthMetrics.grantedKeys()).contains('weight')) {
+ await HealthMetrics.requestKeys(['weight']);
+ if (!(await HealthMetrics.grantedKeys()).contains('weight')) {
+ notifyListeners();
+ return false;
+ }
+ }
+ hcWeights = on;
+ _persist();
+ notifyListeners();
+ if (on) await syncHealthExtras();
+ return true;
+ }
+
+ Future<bool> setHcHeart(bool on) async {
+ if (on && !(await HealthMetrics.grantedKeys()).contains('workoutHr')) {
+ await HealthMetrics.requestKeys(['workoutHr']);
+ if (!(await HealthMetrics.grantedKeys()).contains('workoutHr')) {
+ notifyListeners();
+ return false;
+ }
+ }
+ hcHeart = on;
+ _persist();
+ notifyListeners();
+ if (on) await syncHealthExtras();
+ return true;
+ }
+
+ bool importWeighIns(List<List<double>> rows) {
+ var added = false;
+ for (final r in rows) {
+ final at = DateTime.fromMillisecondsSinceEpoch(r[0].round());
+ final kg = r[1];
+ final key = r[0].round() ~/ 60000;
+ if (!kg.isFinite || kg < 20 || kg > 400 || !hcSeenWeights.add(key)) continue;
+ final dup = bodyweight.any((b) => (b.date.difference(at).inMinutes).abs() <= 120 && (b.kg - kg).abs() < 0.06);
+ if (dup) continue;
+ bodyweight.add(BodyweightEntry(at, (kg * 100).round() / 100));
+ added = true;
+ }
+ if (added) bodyweight.sort((a, b) => a.date.compareTo(b.date));
+ return added;
+ }
+
+ bool applyWorkoutHeart(LoggedSession s, List<List<double>> samples) {
+ final start = s.day.millisecondsSinceEpoch, end = s.date.millisecondsSinceEpoch;
+ final bpm = [
+ for (final r in samples)
+ if (r[0] >= start && r[0] <= end && r[1] > 30 && r[1] < 240) r[1],
+ ];
+ if (bpm.length < 3) return false;
+ s.hrAvg = (bpm.reduce((a, b) => a + b) / bpm.length).round();
+ s.hrMax = bpm.reduce((a, b) => a > b ? a : b).round();
+ return true;
+ }
+
+ Future<void> syncHealthExtras() async {
+ if (!hcWeights && !hcHeart) return;
+ final keys = await HealthMetrics.grantedKeys();
+ final now = DateTime.now();
+ var dirty = false;
+ if (hcWeights && keys.contains('weight')) {
+ final rows = await HealthMetrics.readKey('weight', now.subtract(const Duration(days: 30)), now);
+ if (rows != null && importWeighIns(rows)) dirty = true;
+ }
+ if (hcHeart && keys.contains('workoutHr')) {
+ final since = now.subtract(const Duration(days: 2));
+ for (final s in sessions.where((s) => s.hrAvg == null && s.date.isAfter(since)).toList()) {
+ final rows = await HealthMetrics.readKey('workoutHr', s.day, s.date);
+ if (rows != null && applyWorkoutHeart(s, rows)) dirty = true;
+ }
+ }
+ if (!dirty) return;
+ _persist();
+ notifyListeners();
+ }
List<HealthMetric> get healthMetrics => [for (final m in HealthMetric.values) if (healthShown.contains(m)) m];
@@ -36,11 +187,13 @@ mixin HealthState on FitCore {
}
Future<bool> allowAllHealth() async {
- final missing = [for (final m in HealthMetric.values) if (!healthGranted.contains(m)) m];
+ final missing = [for (final m in HealthMetric.values) if (!healthGranted.contains(m)) m.name];
+ if (!(await HealthMetrics.grantedKeys()).contains('steps')) missing.add('steps');
if (missing.isNotEmpty) {
- await HealthMetrics.request(missing);
+ await HealthMetrics.requestKeys(missing);
healthGranted = await HealthMetrics.granted();
}
+ if ((await HealthMetrics.grantedKeys()).contains('steps')) await stepsAllowed();
final now = [for (final m in HealthMetric.values) if (healthGranted.contains(m)) m];
if (now.isEmpty) {
notifyListeners();
@@ -55,6 +208,12 @@ mixin HealthState on FitCore {
}
void loadHealth(Map<String, dynamic>? j) {
+ hcWeights = j?['w'] == true;
+ hcHeart = j?['hr'] == true;
+ hcWrite = j?['wo'] == true;
+ hcSeenWeights
+ ..clear()
+ ..addAll([for (final k in (j?['seen'] as List?) ?? const []) if (k is num) k.toInt()]);
final byName = HealthMetric.values.asNameMap();
healthShown
..clear()
@@ -74,6 +233,10 @@ mixin HealthState on FitCore {
if (healthShown.isNotEmpty) 'on': [for (final m in healthMetrics) m.name],
if (healthPinned.isNotEmpty) 'pin': [for (final m in healthPinned) m.name],
if (healthByDay.isNotEmpty) 'days': {for (final e in healthByDay.entries) e.key.name: e.value},
+ if (hcWeights) 'w': true,
+ if (hcHeart) 'hr': true,
+ if (hcWrite) 'wo': true,
+ if (hcSeenWeights.isNotEmpty) 'seen': [...hcSeenWeights.toList()..sort()].reversed.take(400).toList(),
};
List<double>? healthOnDay(HealthMetric m, DateTime day) => healthByDay[m]?[HealthMetrics.dayKey(day)];
@@ -93,7 +256,11 @@ mixin HealthState on FitCore {
List<double?> healthSeries(HealthMetric m, int n) =>
[for (final d in healthLastDays(n)) healthOnDay(m, d)?.first];
- Future<void> refreshHealth() => _healthRunning ??= _syncHealth().whenComplete(() => _healthRunning = null);
+ Future<void> refreshHealth() => _healthRunning ??= () async {
+ await _syncHealth();
+ await syncHealthExtras();
+ }()
+ .whenComplete(() => _healthRunning = null);
Future<void> _syncHealth() async {
if (healthShown.isEmpty) return;
@@ -106,7 +273,11 @@ mixin HealthState on FitCore {
for (final m in healthMetrics) {
if (!granted.contains(m)) continue;
final rows = await HealthMetrics.read(m, from, to);
- if (rows == null) continue;
+ if (rows == null) {
+ dirty |= healthFailed.add(m);
+ continue;
+ }
+ dirty |= healthFailed.remove(m);
final days = HealthMetrics.byDay(m, rows);
if (_sameDays(healthByDay[m], days)) continue;
healthByDay[m] = days;
diff --git a/lib/state/steps_state.dart b/lib/state/steps_state.dart
index b2b360d..b07858f 100644
--- a/lib/state/steps_state.dart
+++ b/lib/state/steps_state.dart
@@ -81,6 +81,16 @@ mixin StepsState on FitCore {
return true;
}
+ @override
+ Future<void> stepsAllowed() async {
+ if (!stepsOn) {
+ stepsOn = true;
+ _persist();
+ notifyListeners();
+ }
+ await _freshSteps();
+ }
+
Future<void> askStepsAccess() async {
if (!await HealthSteps.request()) await HealthSteps.openSettings();
await _freshSteps();
diff --git a/lib/widgets/health_cards.dart b/lib/widgets/health_cards.dart
index 7ada575..11f1d60 100644
--- a/lib/widgets/health_cards.dart
+++ b/lib/widgets/health_cards.dart
@@ -1,6 +1,7 @@
import 'dart:math' as math;
import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
import 'package:phosphoricons_flutter/phosphoricons_flutter.dart';
import '../l10n/l10n.dart';
@@ -12,6 +13,7 @@ import '../theme/app_theme.dart';
import 'charts.dart';
import 'entrance.dart';
import 'glass.dart';
+import 'liquid_notch.dart';
import 'nutrition_art.dart' show ValueLineChart;
import 'ui_kit.dart';
@@ -38,18 +40,18 @@ String healthGroupName(HealthGroup g) => switch (g) {
};
IconData healthIcon(HealthMetric m) => switch (m) {
- HealthMetric.restingHr => PhosphorIconsFill.heart,
- HealthMetric.heartRate => PhosphorIconsFill.heartbeat,
- HealthMetric.hrv => PhosphorIconsFill.waveform,
- HealthMetric.spo2 => PhosphorIconsFill.drop,
- HealthMetric.respiration => PhosphorIconsFill.wind,
- HealthMetric.bloodPressure => PhosphorIconsFill.gauge,
- HealthMetric.temperature => PhosphorIconsFill.thermometer,
- HealthMetric.sleep => PhosphorIconsFill.moonStars,
- HealthMetric.distance => PhosphorIconsFill.path,
- HealthMetric.floors => PhosphorIconsFill.stairs,
- HealthMetric.elevation => PhosphorIconsFill.mountains,
- HealthMetric.activeKcal => PhosphorIconsFill.fire,
+ HealthMetric.restingHr => PhosphorIconsRegular.heart,
+ HealthMetric.heartRate => PhosphorIconsRegular.heartbeat,
+ HealthMetric.hrv => PhosphorIconsRegular.waveform,
+ HealthMetric.spo2 => PhosphorIconsRegular.drop,
+ HealthMetric.respiration => PhosphorIconsRegular.wind,
+ HealthMetric.bloodPressure => PhosphorIconsRegular.gauge,
+ HealthMetric.temperature => PhosphorIconsRegular.thermometer,
+ HealthMetric.sleep => PhosphorIconsRegular.moonStars,
+ HealthMetric.distance => PhosphorIconsRegular.path,
+ HealthMetric.floors => PhosphorIconsRegular.stairs,
+ HealthMetric.elevation => PhosphorIconsRegular.mountains,
+ HealthMetric.activeKcal => PhosphorIconsRegular.fire,
};
Color healthTone(GymColors gc, HealthGroup g) => switch (g) {
@@ -256,6 +258,7 @@ class HealthScreen extends StatelessWidget {
style: AppTheme.f(32, weight: FontWeight.w800, color: gc.text, letterSpacing: -0.9, height: 1.05)),
const SizedBox(height: 4),
Text(t.healthFrom, style: AppTheme.f(13, weight: FontWeight.w500, color: gc.textSecondary)),
+ const _HealthLinks(),
for (final g in HealthGroup.values)
if (shown.any((m) => m.group == g))
Column(
@@ -309,10 +312,7 @@ void showHealthPins(BuildContext context) {
constraints: BoxConstraints(maxHeight: MediaQuery.sizeOf(sheet).height * 0.85),
child: Container(
padding: sheetPad(sheet),
- decoration: BoxDecoration(
- color: gc.bgRaised,
- borderRadius: const BorderRadius.vertical(top: Radius.circular(28)),
- ),
+ decoration: sheetDecoration(gc),
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
@@ -425,7 +425,7 @@ class HealthTile extends StatelessWidget {
!granted
? t.healthAllow
: latest == null
- ? t.healthNoData
+ ? (fit.healthFailed.contains(metric) ? t.healthReadFailed : t.healthNoData)
: healthWhen(latest.day),
maxLines: 1,
overflow: TextOverflow.ellipsis,
@@ -459,10 +459,7 @@ void showHealthPicker(BuildContext context) {
constraints: BoxConstraints(maxHeight: MediaQuery.sizeOf(sheet).height * 0.9),
child: Container(
padding: sheetPad(sheet),
- decoration: BoxDecoration(
- color: gc.bgRaised,
- borderRadius: const BorderRadius.vertical(top: Radius.circular(28)),
- ),
+ decoration: sheetDecoration(gc),
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
@@ -495,7 +492,36 @@ void showHealthPicker(BuildContext context) {
),
const SizedBox(height: 6),
Flexible(
- child: SingleChildScrollView(
+ child: FloatingActions(
+ actions: Row(children: [
+ Expanded(
+ child: Pressable(
+ onTap: HealthSteps.openSettings,
+ child: Container(
+ height: 52,
+ padding: const EdgeInsets.symmetric(horizontal: 14),
+ decoration: BoxDecoration(
+ color: gc.bgRaised2,
+ borderRadius: BorderRadius.circular(100),
+ ),
+ child: Row(mainAxisAlignment: MainAxisAlignment.center, children: [
+ Icon(PhosphorIconsRegular.shieldCheck, size: 17, color: gc.text),
+ const SizedBox(width: 8),
+ Flexible(
+ child: Text(t.stepsManage,
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: AppTheme.f(14, weight: FontWeight.w700, color: gc.text)),
+ ),
+ ]),
+ ),
+ ),
+ ),
+ const SizedBox(width: 10),
+ SizedBox(width: 112, child: PrimaryButton(label: t.done, onTap: () => Navigator.of(sheet).pop())),
+ ]),
+ child: SingleChildScrollView(
+ padding: const EdgeInsets.only(bottom: 84),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
@@ -520,17 +546,8 @@ void showHealthPicker(BuildContext context) {
],
),
),
- ),
- const SizedBox(height: 18),
- Center(
- child: GhostButton(
- label: t.stepsManage,
- icon: PhosphorIconsRegular.shieldCheck,
- onTap: HealthSteps.openSettings,
),
),
- const SizedBox(height: 12),
- PrimaryButton(label: t.done, onTap: () => Navigator.of(sheet).pop()),
],
),
),
@@ -584,10 +601,7 @@ void showHealthDetail(BuildContext context, HealthMetric metric) {
backgroundColor: Colors.transparent,
builder: (sheet) => Container(
padding: sheetPad(sheet),
- decoration: BoxDecoration(
- color: gc.bgRaised,
- borderRadius: const BorderRadius.vertical(top: Radius.circular(28)),
- ),
+ decoration: sheetDecoration(gc),
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
@@ -614,7 +628,7 @@ void showHealthDetail(BuildContext context, HealthMetric metric) {
],
),
const SizedBox(height: 4),
- Text(latest == null ? t.healthNoData : healthWhen(latest.day),
+ Text(latest == null ? (fit.healthFailed.contains(metric) ? t.healthReadFailed : t.healthNoData) : healthWhen(latest.day),
textAlign: TextAlign.center,
style: AppTheme.f(12.5, weight: FontWeight.w500, color: gc.textTertiary)),
const SizedBox(height: 20),
@@ -680,3 +694,57 @@ void showHealthDetail(BuildContext context, HealthMetric metric) {
),
);
}
+
+class _HealthLinks extends StatelessWidget {
+ const _HealthLinks();
+
+ @override
+ Widget build(BuildContext context) {
+ final gc = context.gc;
+ Widget row(IconData icon, String title, String hint, bool on, Future<bool> Function(bool) set) => Pressable(
+ scale: 0.98,
+ onTap: () async {
+ HapticFeedback.selectionClick();
+ final ok = await set(!on);
+ if (!ok && context.mounted) {
+ showNotchToast(context, t.healthLinkDenied,
+ icon: PhosphorIconsFill.warningCircle, accent: gc.warn, action: t.healthOpenSettings,
+ onTap: () => HealthSteps.openSettings());
+ }
+ },
+ child: Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 13),
+ child: Row(children: [
+ Icon(icon, size: 18, color: on ? gc.accent : gc.textSecondary),
+ const SizedBox(width: 14),
+ Expanded(
+ child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
+ Text(title, style: AppTheme.f(14.5, weight: FontWeight.w600, color: gc.text)),
+ const SizedBox(height: 2),
+ Text(hint, style: AppTheme.f(11.5, weight: FontWeight.w500, color: gc.textSecondary, height: 1.3)),
+ ]),
+ ),
+ const SizedBox(width: 10),
+ TinySwitch(on: on),
+ ]),
+ ),
+ );
+ return Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [
+ Padding(
+ padding: const EdgeInsets.fromLTRB(4, 24, 0, 10),
+ child: Text(t.healthLinksTitle.toUpperCase(),
+ style: AppTheme.f(10.5, weight: FontWeight.w700, color: gc.textTertiary, letterSpacing: 1.4)),
+ ),
+ Container(
+ decoration: BoxDecoration(color: gc.bgRaised, borderRadius: BorderRadius.circular(22)),
+ child: Column(children: [
+ row(PhosphorIconsRegular.heartbeat, t.healthLinkHeart, t.healthLinkHeartHint, fit.hcHeart, fit.setHcHeart),
+ Divider(height: 1, thickness: 1, color: gc.border, indent: 48),
+ row(PhosphorIconsRegular.scales, t.healthLinkWeight, t.healthLinkWeightHint, fit.hcWeights, fit.setHcWeights),
+ Divider(height: 1, thickness: 1, color: gc.border, indent: 48),
+ row(PhosphorIconsRegular.barbell, t.healthLinkWrite, t.healthLinkWriteHint, fit.hcWrite, fit.setHcWrite),
+ ]),
+ ),
+ ]);
+ }
+}
diff --git a/lib/widgets/steps_card.dart b/lib/widgets/steps_card.dart
index b18c406..b091290 100644
--- a/lib/widgets/steps_card.dart
+++ b/lib/widgets/steps_card.dart
@@ -158,10 +158,7 @@ void showStepsSheet(BuildContext context) {
builder: (sheet) => StatefulBuilder(
builder: (sheet, setSheet) => Container(
padding: sheetPad(sheet),
- decoration: BoxDecoration(
- color: gc.bgRaised,
- borderRadius: const BorderRadius.vertical(top: Radius.circular(28)),
- ),
+ decoration: sheetDecoration(gc),
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
diff --git a/test/health_test.dart b/test/health_test.dart
index 7ce036a..38062ef 100644
--- a/test/health_test.dart
+++ b/test/health_test.dart
@@ -1,4 +1,5 @@
import 'package:flutter_test/flutter_test.dart';
+import 'package:gymmane/models/workout.dart';
import 'package:gymmane/l10n/l10n.dart';
import 'package:gymmane/services/health_metrics.dart';
import 'package:gymmane/services/local_store.dart';
@@ -120,4 +121,80 @@ void main() {
expect(healthValue(HealthMetric.elevation, [100]), '328');
});
});
+
+ group('Health Connect con tus entrenos', () {
+ setUp(() async {
+ SharedPreferences.setMockInitialValues({});
+ await Store.instance.init();
+ fit.resetAllData();
+ });
+
+ test('los pesajes de otras apps entran una vez y no pisan los tuyos', () {
+ final n = DateTime(2026, 10, 20, 8);
+ fit.bodyweight.add(BodyweightEntry(n, 80));
+ final rows = <List<double>>[
+ [n.add(const Duration(minutes: 30)).millisecondsSinceEpoch.toDouble(), 80.02],
+ [n.add(const Duration(days: 1)).millisecondsSinceEpoch.toDouble(), 79.6],
+ [n.add(const Duration(days: 2)).millisecondsSinceEpoch.toDouble(), 900.0],
+ ];
+ expect(fit.importWeighIns(rows), isTrue);
+ expect(fit.bodyweight.map((b) => b.kg), [80, 79.6]);
+ fit.bodyweight.removeLast();
+ expect(fit.importWeighIns(rows), isFalse, reason: 'uno que borraste no vuelve');
+ expect(fit.bodyweight.length, 1);
+ });
+
+ test('el pulso del entreno sale de las muestras de su hora', () {
+ final end = DateTime(2026, 10, 20, 19);
+ final s = LoggedSession(end, 3600, const []);
+ final inside = end.subtract(const Duration(minutes: 30)).millisecondsSinceEpoch.toDouble();
+ final rows = <List<double>>[
+ [inside, 120.0],
+ [inside + 60000, 150.0],
+ [inside + 120000, 165.0],
+ [end.add(const Duration(hours: 1)).millisecondsSinceEpoch.toDouble(), 70.0],
+ ];
+ expect(fit.applyWorkoutHeart(s, rows), isTrue);
+ expect((s.hrAvg, s.hrMax), (145, 165));
+ final back = LoggedSession.fromJson(s.toJson());
+ expect((back.hrAvg, back.hrMax), (145, 165));
+ expect(fit.applyWorkoutHeart(LoggedSession(end, 60, const []), rows.take(1).toList()), isFalse);
+ });
+
+ test('los interruptores se guardan', () {
+ fit.hcHeart = true;
+ fit.hcSeenWeights.add(42);
+ final j = fit.healthJson();
+ fit.loadHealth(null);
+ expect(fit.hcHeart, isFalse);
+ fit.loadHealth(j);
+ expect((fit.hcHeart, fit.hcWeights), (true, false));
+ expect(fit.hcSeenWeights, {42});
+ });
+
+ test('un entreno guardado en Salud lleva un id fijo y el tipo que toca', () {
+ final end = DateTime(2026, 11, 2, 19);
+ LoggedExercise ex(String id) => LoggedExercise(id, id, 'legs', [LoggedSet(0, 0, sec: 1200, km: 3)]);
+ final lift = LoggedSession(end, 3600, [ex('barbell-squat'), ex('running')]);
+ final run = LoggedSession(end, 1800, [ex('running')]);
+ final walk = LoggedSession(end, 1800, [ex('treadmill-incline-walk')]);
+ expect(fit.healthWorkoutType(lift), 'strength');
+ expect(fit.healthWorkoutType(run), 'running');
+ expect(fit.healthWorkoutType(walk), 'treadmill');
+ expect(fit.healthWorkoutType(LoggedSession(end, 60, const [])), 'strength');
+ expect(HealthState.healthWorkoutId(lift), 'gymmane-${end.millisecondsSinceEpoch}');
+ expect(HealthState.healthWorkoutId(lift), HealthState.healthWorkoutId(run),
+ reason: 'mismo final, mismo registro: al reanudarlo se actualiza en vez de duplicarse');
+ expect(fit.healthWorkoutNotes(lift), contains(' · '));
+ });
+
+ test('guardar en Salud se recuerda al reabrir', () {
+ fit.hcWrite = true;
+ final j = fit.healthJson();
+ fit.loadHealth(null);
+ expect(fit.hcWrite, isFalse);
+ fit.loadHealth(j);
+ expect(fit.hcWrite, isTrue);
+ });
+ });
}