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

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