@solutionforest/android-health-connect 0.0.0-stage → 0.3.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. package/AndroidHealthConnect.podspec +20 -0
  2. package/CHANGELOG.md +211 -0
  3. package/LICENSE +20 -0
  4. package/README.md +849 -2
  5. package/SECURITY.md +99 -0
  6. package/android/build.gradle +104 -0
  7. package/android/src/main/AndroidManifest.xml +4 -0
  8. package/android/src/main/java/com/androidhealthconnect/AggregateMapper.kt +521 -0
  9. package/android/src/main/java/com/androidhealthconnect/AndroidHealthConnectModule.kt +637 -0
  10. package/android/src/main/java/com/androidhealthconnect/AndroidHealthConnectPackage.kt +31 -0
  11. package/android/src/main/java/com/androidhealthconnect/AvailabilitySupport.kt +149 -0
  12. package/android/src/main/java/com/androidhealthconnect/ChangesMapper.kt +105 -0
  13. package/android/src/main/java/com/androidhealthconnect/ExtendedRecordMapper.kt +665 -0
  14. package/android/src/main/java/com/androidhealthconnect/FeatureSupport.kt +88 -0
  15. package/android/src/main/java/com/androidhealthconnect/PhrMapper.kt +187 -0
  16. package/android/src/main/java/com/androidhealthconnect/PlannedExerciseMapper.kt +242 -0
  17. package/android/src/main/java/com/androidhealthconnect/RecordMapper.kt +1222 -0
  18. package/app.plugin.js +1 -0
  19. package/docs/assets/logo.jpg +0 -0
  20. package/ios/AndroidHealthConnect.h +5 -0
  21. package/ios/AndroidHealthConnect.mm +21 -0
  22. package/lib/module/NativeAndroidHealthConnect.js +5 -0
  23. package/lib/module/NativeAndroidHealthConnect.js.map +1 -0
  24. package/lib/module/foreground.js +117 -0
  25. package/lib/module/foreground.js.map +1 -0
  26. package/lib/module/helpers.js +280 -0
  27. package/lib/module/helpers.js.map +1 -0
  28. package/lib/module/index.js +354 -0
  29. package/lib/module/index.js.map +1 -0
  30. package/lib/module/package.json +1 -0
  31. package/lib/module/types.js +392 -0
  32. package/lib/module/types.js.map +1 -0
  33. package/lib/module/upgrade.js +101 -0
  34. package/lib/module/upgrade.js.map +1 -0
  35. package/lib/typescript/package.json +1 -0
  36. package/lib/typescript/plugin/src/index.d.ts +14 -0
  37. package/lib/typescript/plugin/src/index.d.ts.map +1 -0
  38. package/lib/typescript/src/NativeAndroidHealthConnect.d.ts +95 -0
  39. package/lib/typescript/src/NativeAndroidHealthConnect.d.ts.map +1 -0
  40. package/lib/typescript/src/foreground.d.ts +43 -0
  41. package/lib/typescript/src/foreground.d.ts.map +1 -0
  42. package/lib/typescript/src/helpers.d.ts +108 -0
  43. package/lib/typescript/src/helpers.d.ts.map +1 -0
  44. package/lib/typescript/src/index.d.ts +208 -0
  45. package/lib/typescript/src/index.d.ts.map +1 -0
  46. package/lib/typescript/src/types.d.ts +1209 -0
  47. package/lib/typescript/src/types.d.ts.map +1 -0
  48. package/lib/typescript/src/upgrade.d.ts +26 -0
  49. package/lib/typescript/src/upgrade.d.ts.map +1 -0
  50. package/package.json +255 -4
  51. package/plugin/build/index.d.ts +13 -0
  52. package/plugin/build/index.js +57 -0
  53. package/plugin/src/index.ts +105 -0
  54. package/src/NativeAndroidHealthConnect.ts +133 -0
  55. package/src/foreground.ts +167 -0
  56. package/src/helpers.ts +373 -0
  57. package/src/index.tsx +623 -0
  58. package/src/types.ts +1525 -0
  59. package/src/upgrade.ts +155 -0
package/README.md CHANGED
@@ -1,3 +1,850 @@
1
- # Temporary Holding Version
1
+ <p align="center">
2
+ <img src="docs/assets/logo.jpg" alt="android-health-connect" width="160" height="160" />
3
+ </p>
2
4
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
5
+ <h1 align="center">android-health-connect</h1>
6
+
7
+ <p align="center">
8
+ <a href="https://github.com/solutionforest/AndroidHealthConnect/actions/workflows/ci.yml"><img src="https://github.com/solutionforest/AndroidHealthConnect/actions/workflows/ci.yml/badge.svg?branch=main" alt="CI" /></a>
9
+ <a href="https://github.com/solutionforest/AndroidHealthConnect/releases"><img src="https://img.shields.io/github/v/release/solutionforest/AndroidHealthConnect" alt="GitHub release" /></a>
10
+ <a href="./LICENSE"><img src="https://img.shields.io/badge/License-MIT-yellow.svg" alt="License: MIT" /></a>
11
+ <a href="https://developer.android.com/health-and-fitness/health-connect"><img src="https://img.shields.io/badge/platform-Android-3DDC84.svg" alt="Platform" /></a>
12
+ <a href="https://reactnative.dev/"><img src="https://img.shields.io/badge/React%20Native-0.84%2B-61DAFB.svg" alt="React Native" /></a>
13
+ <img src="https://img.shields.io/badge/TypeScript-strict-3178C6.svg" alt="TypeScript strict" />
14
+ <img src="https://img.shields.io/badge/coverage-100%25%20lines-brightgreen.svg" alt="Coverage 100% lines" />
15
+ <img src="https://img.shields.io/badge/quality-max--strict-0F172A.svg" alt="Quality max-strict" />
16
+ </p>
17
+
18
+ A React Native library for integrating with [Android Health Connect](https://developer.android.com/health-and-fitness/health-connect) — the unified health & fitness data platform on Android 10+ (API 29+).
19
+
20
+ > **Android only.** This library has no iOS implementation.
21
+
22
+ **Quality** (since 0.3.6): max-strict TypeScript · type-aware ESLint · Jest coverage gates · Kotlin `allWarningsAsErrors` · CI fails on drop. Security model: [SECURITY.md](./SECURITY.md).
23
+
24
+ ## Support
25
+
26
+ | Area | Status | Notes |
27
+ |---|---|---|
28
+ | Android | ✅ Supported | API 29+ / Android 10+ |
29
+ | iOS | ❌ Not supported | No native iOS implementation |
30
+ | React Native New Architecture | ✅ Required | TurboModules / RN 0.84+ |
31
+ | Expo | ✅ Supported | SDK 50+ via config plugin |
32
+ | Bare React Native | ✅ Supported | Manual manifest + rationale setup |
33
+ | Health Connect permissions | ✅ Supported | Request / check / revoke |
34
+ | Read / write / delete records | ✅ Supported | See [Supported record types](#supported-record-types) |
35
+ | Aggregate / bucket queries | ✅ Supported | `aggregateRecord`, `aggregateGroupByDuration`, `aggregateGroupByPeriod` |
36
+ | Exercise routes | ✅ Supported | Write on `ExerciseSession`; read `DATA` / `NO_DATA` / `CONSENT_REQUIRED` + `requestExerciseRoute` |
37
+ | Changelog sync | ✅ Supported | `getChangesToken` / `getChanges` (upsert + delete pages; ~30-day tokens) |
38
+ | Planned exercise | ✅ Supported | `PlannedExerciseSession` when `plannedExercise` feature is available |
39
+ | Library upgrade reminder | ✅ Supported | `checkLibraryUpdate()` + weekly CI (HC SDK / release drift → issue) |
40
+ | CI / quality gates | ✅ GitHub-hosted | lint, typecheck, Jest + Kotlin unit tests, library + Android build, audit |
41
+ | Distribution | ✅ npmjs.org + GitHub Releases | Primary: [npmjs](https://www.npmjs.com/package/@solutionforest/android-health-connect). Mirror: GitHub Packages. Release `.tgz` has SBOM + attestations |
42
+ | CodeQL | ✅ Supported | On `main` PRs/pushes + weekly schedule |
43
+
44
+ ## Requirements
45
+
46
+ This library is a **TurboModule** — it needs **React Native 0.84+** (New Architecture).
47
+ **RN 0.6x / 0.7x / &lt;0.84 are not supported** on either release line.
48
+
49
+ Pick a line by Android toolchain (HC SDK / AGP), not by RN major:
50
+
51
+ | Package | RN | Node | `connect-client` | Min AGP | compileSdk | Branch / tag |
52
+ |---|---|---|---|---|---|---|
53
+ | **[`0.3.14`](https://github.com/solutionforest/AndroidHealthConnect/releases/tag/v0.3.14)** (default) | **≥0.84** | **≥22.11** | **`1.2.0-alpha06`** | **9.1.0** | **37** | `main` |
54
+ | **[`0.2.4`](https://github.com/solutionforest/AndroidHealthConnect/releases/tag/v0.2.4)** (maintenance) | **≥0.84** | **≥22.11** | **`1.1.0`** (stable) | **8.9.1** | **36** | [`release/0.2.x`](https://github.com/solutionforest/AndroidHealthConnect/tree/release/0.2.x) |
55
+
56
+ ```sh
57
+ # npmjs.org (default — no .npmrc needed)
58
+ yarn add @solutionforest/android-health-connect@0.3.14 # AGP 9.1+ / compileSdk 37
59
+ yarn add @solutionforest/android-health-connect@0.2.4 # AGP 8.9.1+ / compileSdk 36 (dist-tag release-0.2)
60
+ ```
61
+
62
+ ### What `0.3.14` (this branch) needs in your host app
63
+
64
+ | Requirement | Value for `0.3.14` |
65
+ |---|---|
66
+ | Install | `@solutionforest/android-health-connect` from **npmjs.org** |
67
+ | Health Connect Jetpack SDK | [`connect-client:1.2.0-alpha06`](https://developer.android.com/jetpack/androidx/releases/health-connect) |
68
+ | Android Gradle Plugin | **9.1.1** (min **9.1.0**) |
69
+ | Gradle | **9.3.1+** (required by AGP 9.1) |
70
+ | compileSdk | **37** |
71
+ | Android OS | 10 (API 29)+ |
72
+ | Health Connect app | Required on Android 9–13; built-in on Android 14+ |
73
+ | React Native | **≥0.84** (New Architecture / TurboModules) — not 0.6x / 0.7x |
74
+ | Node.js | ≥22.11 |
75
+ | Expo (optional) | SDK 50+ |
76
+
77
+ ### Health Connect SDK changelog (context)
78
+
79
+ Official notes ([full changelog](https://developer.android.com/jetpack/androidx/releases/health-connect)):
80
+
81
+ | SDK version | Date | What changed |
82
+ |---|---|---|
83
+ | **1.2.0-alpha06** | 2026-08-26 | Updated Health Connect **release and dev signing certificates** |
84
+ | **1.2.0-alpha05** | 2026-08-12 | Jetpack SDK `minSdk` → API 24; secured intents on Android &lt; 14; signature validation fix |
85
+ | **1.2.0-alpha04** | 2026-04-22 | **Matchmaking APIs** |
86
+ | **1.2.0-alpha03** | 2026-03-25 | Richer exercise fields; change-log `pageSize`; activity intensity |
87
+ | **1.2.0-alpha02** | 2025-10-08 | Additional device type enums |
88
+ | **1.2.0-alpha01** | 2025-07-30 | Skin temperature / mindfulness compat; activity intensity (Android 14+) |
89
+ | **1.1.0** (stable) | 2025-10-08 | First stable `connect-client` |
90
+
91
+ JS API: [42 record types](#supported-record-types), feature checks, Matchmaking, PHR. Feature-gated types need `getFeatureStatus(...) === 'available'`.
92
+
93
+ ## Installation
94
+
95
+ | Registry | Notes |
96
+ |---|---|
97
+ | **[npmjs.org](https://www.npmjs.com/package/@solutionforest/android-health-connect)** | **Primary** — `yarn add` / `npm i` with no `.npmrc` |
98
+ | **[GitHub Packages](https://github.com/orgs/solutionforest/packages?repo_name=AndroidHealthConnect)** | Mirror (`npm.pkg.github.com`) + Release `.tgz` (SBOM / attestations) |
99
+
100
+ ### Install the package
101
+
102
+ ```sh
103
+ # Default (0.3.x): connect-client 1.2.0-alpha06 — needs AGP 9.1+ / compileSdk 37
104
+ yarn add @solutionforest/android-health-connect@0.3.14
105
+ # or
106
+ npm install @solutionforest/android-health-connect@0.3.14
107
+
108
+ # Maintenance (0.2.x): connect-client 1.1.0 stable — AGP 8.9.1+ / compileSdk 36
109
+ yarn add @solutionforest/android-health-connect@release-0.2
110
+ ```
111
+
112
+ Alternatives: install from git (`solutionforest/AndroidHealthConnect#v0.3.14`) or download the Release `.tgz`.
113
+
114
+ Pushing a `v*` tag runs the **Release** workflow: packs `.tgz`, uploads to the GitHub Release, publishes to **npmjs.org** via Trusted Publishing (OIDC), and mirrors to GitHub Packages.
115
+
116
+ <details>
117
+ <summary>Optional: install from GitHub Packages instead</summary>
118
+
119
+ ```ini
120
+ # .npmrc
121
+ @solutionforest:registry=https://npm.pkg.github.com
122
+ //npm.pkg.github.com/:_authToken=YOUR_GITHUB_PAT
123
+ ```
124
+
125
+ Use a classic PAT with `read:packages` (SSO-authorize for `solutionforest` if required).
126
+
127
+ </details>
128
+
129
+ ### Expo setup
130
+
131
+ If you are using **Expo** (SDK 50+), add the library's config plugin to your `app.json` or `app.config.js`. The plugin automatically handles adding the required Health Connect intent filters to your Android manifest.
132
+
133
+ ```json
134
+ {
135
+ "expo": {
136
+ "plugins": [
137
+ [
138
+ "@solutionforest/android-health-connect",
139
+ {
140
+ "permissions": [
141
+ "android.permission.health.READ_STEPS",
142
+ "android.permission.health.WRITE_STEPS",
143
+ "android.permission.health.READ_HEART_RATE"
144
+ ]
145
+ }
146
+ ]
147
+ ]
148
+ }
149
+ }
150
+ ```
151
+
152
+ If you omit `permissions` (or pass `[]`), the plugin still adds the required
153
+ intent-filters but **does not declare any health permissions** — list only what
154
+ your app needs:
155
+
156
+ ```json
157
+ {
158
+ "expo": {
159
+ "plugins": ["@solutionforest/android-health-connect"]
160
+ }
161
+ }
162
+ ```
163
+
164
+ After updating `app.json`, run `npx expo prebuild` to regenerate the native Android project.
165
+
166
+ ### Android setup (bare React Native)
167
+
168
+ #### 1. Declare permissions in your app's `AndroidManifest.xml`
169
+
170
+ Health Connect requires every permission your app uses to be declared in the **host app's** manifest (the library manifest is merged automatically, but you must also add them to your app):
171
+
172
+ ```xml
173
+ <manifest ...>
174
+ <!-- Declare only the permissions your app actually needs -->
175
+ <uses-permission android:name="android.permission.health.READ_STEPS" />
176
+ <uses-permission android:name="android.permission.health.WRITE_STEPS" />
177
+ <uses-permission android:name="android.permission.health.READ_HEART_RATE" />
178
+ <!-- ... other permissions ... -->
179
+
180
+ <application ...>
181
+ <activity android:name=".MainActivity" ...>
182
+ <!-- Required for Health Connect permission rationale (Android ≤ 13) -->
183
+ <intent-filter>
184
+ <action android:name="androidx.health.ACTION_SHOW_PERMISSIONS_RATIONALE" />
185
+ </intent-filter>
186
+
187
+ <!-- Required for Health Connect permission UI (Android 14+) -->
188
+ <intent-filter>
189
+ <action android:name="android.intent.action.VIEW_PERMISSION_USAGE" />
190
+ <category android:name="android.intent.category.HEALTH_PERMISSIONS" />
191
+ </intent-filter>
192
+ </activity>
193
+ </application>
194
+ </manifest>
195
+ ```
196
+
197
+ #### 2. Add Health Connect permission rationale (required)
198
+
199
+ Create `res/values/health_permissions.xml`:
200
+
201
+ ```xml
202
+ <resources>
203
+ <string name="health_permissions_rationale">
204
+ This app uses Health Connect to read and write your health data.
205
+ </string>
206
+ </resources>
207
+ ```
208
+
209
+ ## Usage
210
+
211
+ Runnable host demo (buttons for the flows below): [`example/`](./example/) —
212
+ see [`example/README.md`](./example/README.md) for a first-run checklist.
213
+
214
+ ### Check availability
215
+
216
+ ```ts
217
+ import {
218
+ ensureAvailable,
219
+ isHealthConnectAvailable,
220
+ getHealthConnectAvailability,
221
+ openHealthConnectApp,
222
+ } from '@solutionforest/android-health-connect';
223
+
224
+ // Quick gate — opens Play Store / Settings when notInstalled (default):
225
+ const status = await ensureAvailable();
226
+ if (status !== 'available') {
227
+ // notInstalled (store opened) | notSupported (hide HC UI)
228
+ }
229
+
230
+ // Or check without side effects:
231
+ const availability = await isHealthConnectAvailable();
232
+ // 'available' | 'notInstalled' | 'notSupported'
233
+ if (availability === 'notInstalled') {
234
+ openHealthConnectApp(); // Play Store market:// (or Settings on Android 14+)
235
+ }
236
+
237
+ // Prefer details when diagnosing install vs built-in vs China / HMS:
238
+ const info = await getHealthConnectAvailability();
239
+ // info.provider: 'framework' (Android 14+) | 'apk' (9–13) | 'none'
240
+ // info.sdkStatus: 1 = UNAVAILABLE, 2 = PROVIDER_UPDATE_REQUIRED, 3 = AVAILABLE
241
+ // info.googlePlayServicesAvailable / playStoreAvailable / advice
242
+ ```
243
+
244
+ ### Device & region notes
245
+
246
+ | Situation | What happens | What to do |
247
+ |---|---|---|
248
+ | **Android 14+** | Health Connect is **built into** the system | Use Settings / `openHealthConnectSettings()` |
249
+ | **Android 9–13** | Health Connect is a **Play Store APK** | `openHealthConnectApp()` → Play Store install/update |
250
+ | **`sdkStatus === 3`** | **Available** (not “version too old”) | Safe to call APIs |
251
+ | **Mainland China / no GMS** | HC requires Google Play services; CN Play Storefront does not list HC | `status: 'notSupported'`; hide HC UI — cannot install via Play |
252
+ | **Huawei / HMS without GMS** | Same as no GMS | Unsupported for Health Connect |
253
+ | **Samsung / Xiaomi data gaps** | Vendor apps must **write into** HC; library only reads HC | Enable Health Connect sharing in the vendor app |
254
+
255
+ Official availability: [Check Health Connect availability](https://developer.android.com/health-and-fitness/health-connect/availability).
256
+
257
+ ### Request permissions
258
+
259
+ ```ts
260
+ import {
261
+ requestPermissions,
262
+ Permission,
263
+ } from '@solutionforest/android-health-connect';
264
+
265
+ const needed = [
266
+ Permission.READ_STEPS,
267
+ Permission.WRITE_STEPS,
268
+ Permission.READ_HEART_RATE,
269
+ ];
270
+
271
+ const granted = await requestPermissions(needed);
272
+ console.log('Granted:', granted);
273
+
274
+ // Quick checks (no dialog):
275
+ import {
276
+ hasPermissions,
277
+ missingPermissions,
278
+ ensurePermissions,
279
+ } from '@solutionforest/android-health-connect';
280
+
281
+ if (!(await hasPermissions(needed))) {
282
+ const missing = await missingPermissions(needed);
283
+ console.log('Still missing:', missing);
284
+ }
285
+
286
+ // Or request any missing in one shot:
287
+ const ensured = await ensurePermissions(needed);
288
+ if (!ensured.allGranted) {
289
+ console.log('User denied:', ensured.missing);
290
+ }
291
+ ```
292
+
293
+ **History / background (optional special permissions):** by default HC only lets apps
294
+ read ~30 days before first grant, and only while foregrounded. Declare in the host
295
+ manifest, gate on feature status, then request:
296
+
297
+ ```ts
298
+ import {
299
+ getFeatureStatus,
300
+ requestPermissions,
301
+ Permission,
302
+ } from '@solutionforest/android-health-connect';
303
+
304
+ import type { HealthPermission } from '@solutionforest/android-health-connect';
305
+
306
+ const extra: HealthPermission[] = [];
307
+ if ((await getFeatureStatus('readHealthDataHistory')) === 'available') {
308
+ extra.push(Permission.READ_HEALTH_DATA_HISTORY);
309
+ }
310
+ if ((await getFeatureStatus('readHealthDataInBackground')) === 'available') {
311
+ extra.push(Permission.READ_HEALTH_DATA_IN_BACKGROUND);
312
+ }
313
+ await requestPermissions([Permission.READ_STEPS, ...extra]);
314
+ ```
315
+
316
+ ```xml
317
+ <uses-permission android:name="android.permission.health.READ_HEALTH_DATA_HISTORY" />
318
+ <uses-permission android:name="android.permission.health.READ_HEALTH_DATA_IN_BACKGROUND" />
319
+ ```
320
+
321
+ ### Read records
322
+
323
+ ```ts
324
+ import { readSteps, readHeartRate } from '@solutionforest/android-health-connect';
325
+
326
+ const { records, pageToken } = await readSteps({
327
+ timeRangeFilter: {
328
+ startTime: '2024-01-01T00:00:00Z',
329
+ endTime: '2024-01-08T00:00:00Z',
330
+ },
331
+ ascendingOrder: true,
332
+ pageSize: 100,
333
+ });
334
+
335
+ records.forEach(r => console.log(r.count, r.startTime));
336
+ ```
337
+
338
+ Using the generic helper:
339
+
340
+ ```ts
341
+ import { readRecords } from '@solutionforest/android-health-connect';
342
+ import type { WeightRecord } from '@solutionforest/android-health-connect';
343
+
344
+ const { records } = await readRecords<WeightRecord>('Weight', {
345
+ timeRangeFilter: { startTime: '...', endTime: '...' },
346
+ });
347
+ ```
348
+
349
+ ### Write records
350
+
351
+ ```ts
352
+ import { writeRecords } from '@solutionforest/android-health-connect';
353
+
354
+ const { recordIdsList } = await writeRecords([
355
+ {
356
+ recordType: 'Steps',
357
+ count: 8000,
358
+ startTime: '2024-01-01T08:00:00Z',
359
+ endTime: '2024-01-01T09:00:00Z',
360
+ },
361
+ {
362
+ recordType: 'Weight',
363
+ weight: 75.5, // kg
364
+ time: '2024-01-01T07:30:00Z',
365
+ },
366
+ ]);
367
+ ```
368
+
369
+ ### Update records
370
+
371
+ `updateRecords` edits existing rows. Pass the same shape as write, plus
372
+ `metadata.id` from a prior read (required). Optional `recordingMethod` / `device`
373
+ round-trip when present on the read record.
374
+
375
+ ```ts
376
+ import {
377
+ readSteps,
378
+ updateRecords,
379
+ RecordingMethod,
380
+ } from '@solutionforest/android-health-connect';
381
+
382
+ const { records } = await readSteps({
383
+ timeRangeFilter: { startTime: '...', endTime: '...' },
384
+ });
385
+ const existing = records[0];
386
+ if (!existing?.metadata?.id) throw new Error('nothing to update');
387
+
388
+ await updateRecords([
389
+ {
390
+ ...existing,
391
+ count: existing.count + 100,
392
+ metadata: {
393
+ ...existing.metadata,
394
+ id: existing.metadata.id,
395
+ recordingMethod: existing.metadata.recordingMethod ?? RecordingMethod.MANUAL_ENTRY,
396
+ },
397
+ },
398
+ ]);
399
+ ```
400
+
401
+ ### Exercise routes
402
+
403
+ Requires `WRITE_EXERCISE_ROUTE` to insert a route with a session, and
404
+ `READ_EXERCISE_ROUTES` to read routes written by other apps. Omit optional
405
+ altitude / accuracy fields instead of sending empty objects.
406
+
407
+ ```ts
408
+ import {
409
+ writeRecords,
410
+ readExerciseSessions,
411
+ requestExerciseRoute,
412
+ getFeatureStatus,
413
+ ExerciseType,
414
+ } from '@solutionforest/android-health-connect';
415
+
416
+ await writeRecords([
417
+ {
418
+ recordType: 'ExerciseSession',
419
+ exerciseType: ExerciseType.RUNNING,
420
+ startTime: '2024-01-01T08:00:00Z',
421
+ endTime: '2024-01-01T09:00:00Z',
422
+ exerciseRoute: {
423
+ route: [
424
+ { time: '2024-01-01T08:00:00Z', latitude: 51.5, longitude: -0.12, altitude: 19 },
425
+ { time: '2024-01-01T08:30:00Z', latitude: 51.51, longitude: -0.11 },
426
+ ],
427
+ },
428
+ },
429
+ ]);
430
+
431
+ // Optional 1.2 fields — gate on FEATURE_EXERCISE_SESSION_IMPROVEMENTS:
432
+ if ((await getFeatureStatus('exerciseSessionImprovements')) === 'available') {
433
+ await writeRecords([
434
+ {
435
+ recordType: 'ExerciseSession',
436
+ exerciseType: ExerciseType.RUNNING,
437
+ startTime: '2024-01-01T08:00:00Z',
438
+ endTime: '2024-01-01T09:00:00Z',
439
+ rateOfPerceivedExertion: 6.5,
440
+ // plannedExerciseSessionId: '<id from PlannedExerciseSession write>',
441
+ },
442
+ ]);
443
+ }
444
+
445
+ const { records } = await readExerciseSessions({ /* timeRangeFilter … */ });
446
+ for (const session of records) {
447
+ const route = session.exerciseRoute;
448
+ if (!route || route.type === 'NO_DATA') continue;
449
+ if (route.type === 'CONSENT_REQUIRED') {
450
+ const granted = await requestExerciseRoute(session.metadata?.id ?? '');
451
+ console.log(granted?.route);
452
+ } else {
453
+ console.log(route.route); // LengthResult altitude / accuracy when present
454
+ }
455
+ }
456
+ ```
457
+
458
+ ### Planned exercise (training plans)
459
+
460
+ Requires `getFeatureStatus('plannedExercise') === 'available'` and
461
+ `READ_PLANNED_EXERCISE` / `WRITE_PLANNED_EXERCISE`.
462
+
463
+ ```ts
464
+ import {
465
+ requestPermissions,
466
+ writeRecords,
467
+ readPlannedExerciseSessions,
468
+ ExerciseType,
469
+ ExerciseSegmentType,
470
+ ExercisePhase,
471
+ Permission,
472
+ } from '@solutionforest/android-health-connect';
473
+
474
+ await requestPermissions([
475
+ Permission.READ_PLANNED_EXERCISE,
476
+ Permission.WRITE_PLANNED_EXERCISE,
477
+ ]);
478
+
479
+ await writeRecords([
480
+ {
481
+ recordType: 'PlannedExerciseSession',
482
+ exerciseType: ExerciseType.RUNNING,
483
+ startTime: '2024-01-03T08:00:00Z',
484
+ endTime: '2024-01-03T09:30:00Z',
485
+ title: 'Lake run',
486
+ blocks: [
487
+ {
488
+ repetitions: 1,
489
+ description: 'Three laps',
490
+ steps: [
491
+ {
492
+ exerciseType: ExerciseSegmentType.RUNNING,
493
+ exercisePhase: ExercisePhase.ACTIVE,
494
+ completionGoal: { type: 'Repetitions', repetitions: 3 },
495
+ performanceTargets: [
496
+ { type: 'HeartRate', minHeartRate: 90, maxHeartRate: 110 },
497
+ ],
498
+ },
499
+ ],
500
+ },
501
+ ],
502
+ },
503
+ ]);
504
+
505
+ await readPlannedExerciseSessions({ /* timeRangeFilter … */ });
506
+ ```
507
+
508
+ ### Time ranges & waiting for data (resume → often `0` first)
509
+
510
+ Health Connect has **no push observer**. On a real phone, after you **resume /
511
+ re-open the app**, the first read or aggregate is often `0` / empty — vendor apps
512
+ (Samsung Health, Fitbit, …) may still be writing into HC. Google’s guidance: sync
513
+ when the app becomes foreground, and optionally poll while it stays open.
514
+
515
+ `useForegroundPoll` does this for you: it polls on mount and on every resume,
516
+ aborts the in-flight poll when the app backgrounds (so a stale result never
517
+ overwrites a newer one), and keeps the last value on timeout.
518
+
519
+ ```tsx
520
+ import {
521
+ aggregateRecord,
522
+ timeRangeToday,
523
+ useForegroundPoll,
524
+ } from '@solutionforest/android-health-connect';
525
+
526
+ const stepsOf = (r: { metrics: Record<string, unknown> }) => {
527
+ const n = r.metrics['COUNT_TOTAL'];
528
+ return typeof n === 'number' ? n : 0;
529
+ };
530
+
531
+ function TodaySteps({ granted }: { granted: boolean }) {
532
+ const { value, satisfied, loading, error, refresh } = useForegroundPoll(
533
+ () =>
534
+ aggregateRecord({ recordType: 'Steps', timeRangeFilter: timeRangeToday() }),
535
+ {
536
+ // "> 0" only when you expect activity; a real 0-step day times out.
537
+ ready: (r) => stepsOf(r) > 0,
538
+ timeoutMs: 20_000,
539
+ intervalMs: 1_000,
540
+ enabled: granted, // wait until permissions are granted
541
+ }
542
+ );
543
+
544
+ if (error) return <Text onPress={refresh}>Couldn’t read steps. Tap to retry</Text>;
545
+ return (
546
+ <Text onPress={refresh}>
547
+ {value ? stepsOf(value) : '–'} steps
548
+ {loading ? ' · syncing…' : !satisfied && value ? ' · no new data yet' : ''}
549
+ </Text>
550
+ );
551
+ }
552
+ ```
553
+
554
+ Outside React, use `pollOnForeground(fetch, { ready, onResult, onError })`;
555
+ it returns `{ refresh, stop }`. For a single one-off wait, use
556
+ `pollUntil` (soft) or `waitUntil` (throws `WaitTimeoutError`).
557
+
558
+ ```ts
559
+ import {
560
+ timeRangeLastDays,
561
+ waitForRecords,
562
+ readAllRecords,
563
+ } from '@solutionforest/android-health-connect';
564
+
565
+ // After your own writeRecords — wait until the row is readable:
566
+ await waitForRecords({
567
+ recordType: 'Steps',
568
+ timeRangeFilter: timeRangeLastDays(1),
569
+ minCount: 1,
570
+ timeoutMs: 15_000,
571
+ });
572
+
573
+ const all = await readAllRecords('Steps', {
574
+ timeRangeFilter: timeRangeLastDays(7),
575
+ });
576
+ ```
577
+
578
+ ### Aggregates
579
+
580
+ `aggregateRecord` uses Instant time ranges. Prefer
581
+ `aggregateGroupByDuration` for fixed buckets (also Instant — avoids Android 14+
582
+ UTC wall-clock shift). Use `aggregateGroupByPeriod` for calendar days/weeks
583
+ (LocalDateTime in the device zone).
584
+
585
+ ```ts
586
+ import {
587
+ aggregateRecord,
588
+ aggregateGroupByDuration,
589
+ timeRangeLastDays,
590
+ } from '@solutionforest/android-health-connect';
591
+
592
+ const total = await aggregateRecord({
593
+ recordType: 'Steps',
594
+ timeRangeFilter: timeRangeLastDays(7),
595
+ });
596
+ console.log(total.metrics['COUNT_TOTAL']); // number | null
597
+
598
+ const hourly = await aggregateGroupByDuration({
599
+ recordType: 'Steps',
600
+ timeRangeFilter: {
601
+ startTime: '2024-01-01T00:00:00Z',
602
+ endTime: '2024-01-02T00:00:00Z',
603
+ },
604
+ timeRangeSlicer: { unit: 'hours', value: 1 },
605
+ });
606
+ hourly.forEach((row) => {
607
+ console.log(row.startTime, row.result.metrics['COUNT_TOTAL']);
608
+ });
609
+ ```
610
+
611
+ ### Delete records
612
+
613
+ ```ts
614
+ import { deleteRecordsByTime, deleteRecordsById } from '@solutionforest/android-health-connect';
615
+
616
+ // By time range
617
+ await deleteRecordsByTime('Steps', '2024-01-01T00:00:00Z', '2024-01-02T00:00:00Z');
618
+
619
+ // By ID
620
+ await deleteRecordsById('Steps', ['record-id-1', 'record-id-2']);
621
+ ```
622
+
623
+ ### Changelog sync
624
+
625
+ Tokens expire after ~30 days. Prefer **one record type per token**. Loop while
626
+ `hasMore`; if `changesTokenExpired`, backfill with `readRecords` then mint a new
627
+ token. Optional `pageSize` (1–5000) is a soft hint.
628
+
629
+ ```ts
630
+ import {
631
+ getChangesToken,
632
+ pullChanges,
633
+ } from '@solutionforest/android-health-connect';
634
+
635
+ let token = await getChangesToken({ recordTypes: ['Steps'] });
636
+ const batch = await pullChanges(token, { pageSize: 500 });
637
+ if (batch.changesTokenExpired) {
638
+ // backfill with readRecords, then mint a fresh token
639
+ token = await getChangesToken({ recordTypes: ['Steps'] });
640
+ } else {
641
+ for (const { record } of batch.upsertionChanges) {
642
+ console.log('upsert', record.recordType, record.metadata?.id);
643
+ }
644
+ for (const { recordId } of batch.deletionChanges) {
645
+ console.log('delete', recordId);
646
+ }
647
+ token = batch.nextChangesToken; // persist for next sync
648
+ }
649
+ ```
650
+
651
+ ## Supported record types
652
+
653
+ > The 19 parity-batch types marked below are unit-tested but
654
+ > **⚠️ not fully tested on a real device yet**.
655
+
656
+ | Record type | Read | Write | Notes |
657
+ |---|---|---|---|
658
+ | `Steps` | ✅ | ✅ | |
659
+ | `HeartRate` | ✅ | ✅ | |
660
+ | `SleepSession` | ✅ | ✅ | |
661
+ | `ActiveCaloriesBurned` | ✅ | ✅ | |
662
+ | `TotalCaloriesBurned` | ✅ | ✅ | |
663
+ | `Distance` | ✅ | ✅ | |
664
+ | `Weight` | ✅ | ✅ | |
665
+ | `Height` | ✅ | ✅ | |
666
+ | `BloodPressure` | ✅ | ✅ | |
667
+ | `BloodGlucose` | ✅ | ✅ | |
668
+ | `OxygenSaturation` | ✅ | ✅ | |
669
+ | `BodyTemperature` | ✅ | ✅ | |
670
+ | `BodyFat` | ✅ | ✅ | |
671
+ | `Hydration` | ✅ | ✅ | |
672
+ | `ExerciseSession` | ✅ | ✅ | Optional `exerciseRoute`; read returns `DATA` / `NO_DATA` / `CONSENT_REQUIRED`; optional RPE / `plannedExerciseSessionId` when `exerciseSessionImprovements` |
673
+ | `PlannedExerciseSession` | ✅ | ✅ | Requires `getFeatureStatus('plannedExercise')`; blocks / steps / goals / targets |
674
+ | `RestingHeartRate` | ✅ | ✅ | |
675
+ | `RespiratoryRate` | ✅ | ✅ | |
676
+ | `FloorsClimbed` | ✅ | ✅ | |
677
+ | `ElevationGained` | ✅ | ✅ | |
678
+ | `MindfulnessSession` | ✅ | ✅ | Requires `getFeatureStatus('mindfulnessSession')` |
679
+ | `SkinTemperature` | ✅ | ✅ | Requires `getFeatureStatus('skinTemperature')` |
680
+ | `ActivityIntensity` | ✅ | ✅ | Requires `getFeatureStatus('activityIntensity')` |
681
+ | `Nutrition` | ✅ | ✅ | ⚠️ Not fully tested on a real device yet |
682
+ | `Vo2Max` | ✅ | ✅ | ⚠️ Not fully tested on a real device yet |
683
+ | `Speed` | ✅ | ✅ | ⚠️ Not fully tested on a real device yet |
684
+ | `Power` | ✅ | ✅ | ⚠️ Not fully tested on a real device yet |
685
+ | `StepsCadence` | ✅ | ✅ | ⚠️ Not fully tested on a real device yet; uses steps permission |
686
+ | `CyclingPedalingCadence` | ✅ | ✅ | ⚠️ Not fully tested on a real device yet; uses exercise permission |
687
+ | `WheelchairPushes` | ✅ | ✅ | ⚠️ Not fully tested on a real device yet |
688
+ | `MenstruationFlow` | ✅ | ✅ | ⚠️ Not fully tested on a real device yet; shares menstruation permission |
689
+ | `MenstruationPeriod` | ✅ | ✅ | ⚠️ Not fully tested on a real device yet; shares menstruation permission |
690
+ | `OvulationTest` | ✅ | ✅ | ⚠️ Not fully tested on a real device yet |
691
+ | `CervicalMucus` | ✅ | ✅ | ⚠️ Not fully tested on a real device yet |
692
+ | `IntermenstrualBleeding` | ✅ | ✅ | ⚠️ Not fully tested on a real device yet |
693
+ | `SexualActivity` | ✅ | ✅ | ⚠️ Not fully tested on a real device yet |
694
+ | `BasalBodyTemperature` | ✅ | ✅ | ⚠️ Not fully tested on a real device yet |
695
+ | `LeanBodyMass` | ✅ | ✅ | ⚠️ Not fully tested on a real device yet |
696
+ | `BoneMass` | ✅ | ✅ | ⚠️ Not fully tested on a real device yet |
697
+ | `BodyWaterMass` | ✅ | ✅ | ⚠️ Not fully tested on a real device yet |
698
+ | `BasalMetabolicRate` | ✅ | ✅ | ⚠️ Not fully tested on a real device yet |
699
+ | `HeartRateVariabilityRmssd` | ✅ | ✅ | ⚠️ Not fully tested on a real device yet |
700
+
701
+ ### Feature-gated APIs
702
+
703
+ ```ts
704
+ import {
705
+ getFeatureStatus,
706
+ checkIfMatchmakingIsPossible,
707
+ launchMatchmaking,
708
+ createMedicalDataSource,
709
+ upsertMedicalResources,
710
+ readMedicalResources,
711
+ MedicalResourceType,
712
+ } from '@solutionforest/android-health-connect';
713
+
714
+ // Feature availability (skin temperature, mindfulness, activity intensity, matchmaking, PHR, …)
715
+ const skinTemp = await getFeatureStatus('skinTemperature'); // 'available' | 'unavailable'
716
+
717
+ // Matchmaking (experimental) — discover apps/devices that can write data you can read
718
+ if ((await getFeatureStatus('matchmaking')) === 'available') {
719
+ const { isMatchmakingPossible } = await checkIfMatchmakingIsPossible({
720
+ recordTypes: ['Steps', 'HeartRate'],
721
+ });
722
+ if (isMatchmakingPossible) {
723
+ await launchMatchmaking({ recordTypes: ['Steps', 'HeartRate'] });
724
+ }
725
+ }
726
+
727
+ // Personal Health Record / medical (experimental) — FHIR MedicalDataSource + MedicalResource
728
+ if ((await getFeatureStatus('personalHealthRecord')) === 'available') {
729
+ const source = await createMedicalDataSource({
730
+ displayName: 'Clinic FHIR',
731
+ fhirBaseUri: 'https://example.com/fhir/',
732
+ fhirVersion: { major: 4, minor: 0, patch: 1 },
733
+ });
734
+ await upsertMedicalResources([
735
+ {
736
+ dataSourceId: source.id,
737
+ fhirVersion: source.fhirVersion,
738
+ data: JSON.stringify({ resourceType: 'AllergyIntolerance', id: '1', /* … */ }),
739
+ },
740
+ ]);
741
+ const page = await readMedicalResources({
742
+ medicalResourceType: MedicalResourceType.ALLERGIES_INTOLERANCES,
743
+ medicalDataSourceIds: [source.id],
744
+ });
745
+ }
746
+ ```
747
+
748
+ ## Upgrade reminders
749
+
750
+ Check GitHub Releases and show a reminder when a newer library version is available:
751
+
752
+ ```ts
753
+ import { checkLibraryUpdate, LIBRARY_VERSION } from '@solutionforest/android-health-connect';
754
+
755
+ const update = await checkLibraryUpdate();
756
+ if (update.updateAvailable) {
757
+ console.warn(update.advice);
758
+ // e.g. show in-app banner: update.currentVersion → update.latestVersion
759
+ }
760
+ ```
761
+
762
+ ## Maintainers
763
+
764
+ | Workflow | What it does |
765
+ |---|---|
766
+ | **CI** / **CodeQL** | Lint, tests, build on `ubuntu-latest` |
767
+ | **Version check** | Mondays 08:00 UTC — compares HC SDK (Maven) + library (GitHub Release); opens/updates an `upgrade-reminder` issue. Manual: **Actions → Version check → Run workflow**. Cron options in `.github/workflows/version-check.yml`. |
768
+ | **Release** (`v*` tag) | Packs `.tgz` + SBOM / attestations → GitHub Release → **npmjs.org** (OIDC Trusted Publishing) → GitHub Packages mirror |
769
+
770
+ ## API reference
771
+
772
+ ### Availability
773
+
774
+ | Function | Returns | Description |
775
+ |---|---|---|
776
+ | `isHealthConnectAvailable()` | `Promise<HealthConnectAvailability>` | Check if HC is usable |
777
+ | `getHealthConnectAvailability()` | `Promise<HealthConnectAvailabilityInfo>` | Detailed status (framework/apk, GMS, Play Store, advice) |
778
+ | `openHealthConnectApp()` | `void` | Open HC app or Play Store |
779
+ | `openHealthConnectSettings()` | `void` | Open HC settings |
780
+ | `openHealthConnectDataManagement(pkg?)` | `void` | Open permission management |
781
+ | `checkLibraryUpdate(options?)` | `Promise<LibraryUpdateInfo>` | Upgrade reminder vs GitHub Releases |
782
+ | `LIBRARY_VERSION` | `string` | Current package version |
783
+
784
+ ### Permissions
785
+
786
+ | Function | Returns | Description |
787
+ |---|---|---|
788
+ | `requestPermissions(perms)` | `Promise<string[]>` | Show permission dialog |
789
+ | `checkPermissions(perms)` | `Promise<string[]>` | Check which are granted |
790
+ | `hasPermissions(perms)` | `Promise<boolean>` | True when all listed perms are granted |
791
+ | `missingPermissions(perms)` | `Promise<string[]>` | Subset that is not granted |
792
+ | `ensurePermissions(perms, opts?)` | `Promise<EnsurePermissionsResult>` | Request any missing (default) + re-check |
793
+ | `ensureAvailable(opts?)` | `Promise<availability>` | Quick gate; opens store if `notInstalled` (default) |
794
+ | `revokeAllPermissions()` | `Promise<void>` | Revoke all permissions |
795
+ | `Permission.*` | `HealthPermission` | Typed permission string constants |
796
+ | `timeRangeToday()` / `timeRangeLastDays(n)` / `timeRangeLastHours(n)` | `TimeRangeFilter` | Instant windows for reads/aggregates |
797
+ | `pollUntil(fetch, opts)` | `Promise<PollUntilResult>` | Soft poll (resume: first value often `0`) |
798
+ | `waitUntil(fetch, opts)` | `Promise<T>` | Same as pollUntil but throws on timeout |
799
+ | `useForegroundPoll(fetch, opts)` | `{ value, satisfied, loading, error, refresh }` | React hook: poll on mount + every resume |
800
+ | `pollOnForeground(fetch, opts)` | `{ refresh, stop }` | Non-React version of `useForegroundPoll` |
801
+ | `waitForRecords(opts)` | `Promise<ReadRecordsResponse>` | Poll `readRecords` until rows appear |
802
+ | `readAllRecords(type, opts?)` | `Promise<T[]>` | Follow `pageToken` until exhausted |
803
+ | `pullChanges(token, opts?)` | `Promise<PullChangesResult>` | Drain changelog pages (`hasMore` loop) |
804
+
805
+ ### Records
806
+
807
+ | Function | Returns | Description |
808
+ |---|---|---|
809
+ | `readRecords<T>(type, options)` | `Promise<ReadRecordsResponse<T>>` | Generic read |
810
+ | `writeRecords(records)` | `Promise<InsertRecordsResponse>` | Insert records |
811
+ | `updateRecords(records)` | `Promise<void>` | Update existing records (`metadata.id` required) |
812
+ | `deleteRecordsByTime(type, start, end)` | `Promise<void>` | Delete by time range |
813
+ | `deleteRecordsById(type, ids)` | `Promise<void>` | Delete by IDs |
814
+ | `aggregateRecord(request)` | `Promise<AggregateResult>` | Sum/avg/min/max over Instant range |
815
+ | `aggregateGroupByDuration(request)` | `Promise<AggregationResultGroupedByDuration[]>` | Fixed buckets (Instant; avoids UTC shift) |
816
+ | `aggregateGroupByPeriod(request)` | `Promise<AggregationResultGroupedByPeriod[]>` | Calendar buckets (LocalDateTime) |
817
+ | `requestExerciseRoute(recordId)` | `Promise<ExerciseRouteRead \| null>` | Consent UI when route is `CONSENT_REQUIRED` |
818
+ | `getChangesToken(request)` | `Promise<string>` | Mint changelog token (~30 days; prefer one type) |
819
+ | `getChanges(token, opts?)` | `Promise<GetChangesResponse>` | Upserts/deletes since token; optional `pageSize` (1–5000) |
820
+ | `readSteps(options?)` | `Promise<ReadRecordsResponse<StepsRecord>>` | Convenience helper |
821
+ | `readHeartRate(options?)` | … | Convenience helper |
822
+ | *(and one per record type, including Mindfulness / SkinTemperature / ActivityIntensity)* | | |
823
+
824
+ ### Features / Matchmaking / PHR
825
+
826
+ | Function | Returns | Description |
827
+ |---|---|---|
828
+ | `getFeatureStatus(feature)` | `Promise<'available' \| 'unavailable'>` | Check HC feature flags |
829
+ | `checkIfMatchmakingIsPossible(opts?)` | `Promise<{ isMatchmakingPossible }>` | Whether Matchmaking UI has candidates |
830
+ | `launchMatchmaking(opts?)` | `Promise<boolean>` | Launch Matchmaking activity |
831
+ | `createMedicalDataSource(req)` | `Promise<MedicalDataSource>` | Create FHIR data source |
832
+ | `getMedicalDataSources(req?)` | `Promise<MedicalDataSource[]>` | List medical data sources |
833
+ | `deleteMedicalDataSourceWithData(id)` | `Promise<void>` | Delete source + its resources |
834
+ | `upsertMedicalResources(reqs)` | `Promise<MedicalResource[]>` | Insert/update FHIR resources |
835
+ | `readMedicalResources(req)` | `Promise<ReadMedicalResourcesResponse>` | Paged medical resource read |
836
+ | `deleteMedicalResources(req)` | `Promise<void>` | Delete by IDs or filters |
837
+
838
+ ## Contributing
839
+
840
+ - [Development workflow](CONTRIBUTING.md#development-workflow)
841
+ - [Sending a pull request](CONTRIBUTING.md#sending-a-pull-request)
842
+ - [Code of conduct](CODE_OF_CONDUCT.md)
843
+
844
+ ## License
845
+
846
+ MIT
847
+
848
+ ---
849
+
850
+ Made with [create-react-native-library](https://github.com/callstack/react-native-builder-bob)