@asiriindatissa/capacitor-health 8.4.4 → 9.0.0

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.
package/README.md CHANGED
@@ -1,18 +1,17 @@
1
1
  # @asiriindatissa/capacitor-health
2
2
 
3
- Capacitor plugin to read and write health metrics via Health Connect on Android. The TypeScript API provides a unified interface for health data access.
3
+ Capacitor plugin to read sleep and hydration data via Health Connect on Android. The TypeScript API provides a unified interface for health data access.
4
4
 
5
5
  ## Why Capacitor Health?
6
6
 
7
7
  The only **free**, **unified** health data plugin for Capacitor supporting the latest native APIs:
8
8
 
9
- - **Health Connect (Android)** - Uses Google's newest health platform (replaces deprecated Google Fit)
9
+ - **Health Connect (Android)** - Uses Google's newest health platform
10
10
  - **Unified API** - TypeScript interface with consistent units
11
- - **Multiple metrics** - Steps, distance, calories, heart rate, weight, height
12
- - **Read & Write** - Query historical data and save new health entries
11
+ - **Sleep & Hydration** - Query sleep sessions and hydration records
13
12
  - **Modern standards** - Supports Android 8.0+
14
13
 
15
- Perfect for fitness apps, health trackers, wellness platforms, and medical applications.
14
+ Perfect for wellness apps, sleep trackers, and health applications.
16
15
 
17
16
  ## Install
18
17
 
@@ -26,13 +25,11 @@ npx cap sync
26
25
  This plugin now uses [Health Connect](https://developer.android.com/health-and-fitness/guides/health-connect) instead of Google Fit. Make sure your app meets the requirements below:
27
26
 
28
27
  1. **Min SDK 26+.** Health Connect is only available on Android 8.0 (API 26) and above. The plugin's Gradle setup already targets this level.
29
- 2. **Declare Health permissions.** The plugin manifest ships with the required `<uses-permission>` declarations (`READ_/WRITE_STEPS`, `READ_/WRITE_DISTANCE`, `READ_/WRITE_ACTIVE_CALORIES_BURNED`, `READ_/WRITE_HEART_RATE`, `READ_/WRITE_WEIGHT`, `READ_/WRITE_HEIGHT`, `READ_EXERCISE`). Your app does not need to duplicate them, but you must surface a user-facing rationale because the permissions are considered health sensitive.
28
+ 2. **Declare Health permissions.** The plugin manifest ships with the required `<uses-permission>` declarations (`READ_SLEEP`, `READ_HYDRATION`). Your app does not need to duplicate them, but you must surface a user-facing rationale because the permissions are considered health sensitive.
30
29
  3. **Ensure Health Connect is installed.** Devices on Android 14+ include it by default. For earlier versions the user must install _Health Connect by Android_ from the Play Store. The `Health.isAvailable()` helper exposes the current status so you can prompt accordingly.
31
30
  4. **Request runtime access.** The plugin opens the Health Connect permission UI when you call `requestAuthorization`. You should still handle denial flows (e.g., show a message if `checkAuthorization` reports missing scopes).
32
31
  5. **Provide a Privacy Policy.** Health Connect requires apps to display a privacy policy explaining how health data is used. See the [Privacy Policy Setup](#privacy-policy-setup) section below.
33
32
 
34
- If you already used Google Fit in your project you can remove the associated dependencies (`play-services-fitness`, `play-services-auth`, OAuth configuration, etc.).
35
-
36
33
  ### Privacy Policy Setup
37
34
 
38
35
  Health Connect requires your app to provide a privacy policy that explains how you handle health data. When users tap "Privacy policy" in the Health Connect permissions dialog, your app must display this information.
@@ -53,7 +50,7 @@ Place an HTML file at `android/app/src/main/assets/public/privacypolicy.html`:
53
50
  <h1>Privacy Policy</h1>
54
51
  <p>Your privacy policy content here...</p>
55
52
  <h2>Health Data</h2>
56
- <p>Explain how you collect, use, and protect health data...</p>
53
+ <p>Explain how you collect, use, and protect sleep and hydration data...</p>
57
54
  </body>
58
55
  </html>
59
56
  ```
@@ -94,74 +91,26 @@ if (!availability.available) {
94
91
  console.warn('Health access unavailable:', availability.reason);
95
92
  }
96
93
 
97
- // Ask for separate read/write access scopes
98
- // Include 'workouts' if you need to query workout sessions
99
- await Health.requestAuthorization({
100
- read: ['steps', 'heartRate', 'weight', 'totalCalories', 'workouts'],
101
- write: ['weight'],
102
- });
103
-
104
- // Query the last 50 step samples from the past 24 hours
105
- const { samples } = await Health.readSamples({
106
- dataType: 'steps',
107
- startDate: new Date(Date.now() - 24 * 60 * 60 * 1000).toISOString(),
108
- endDate: new Date().toISOString(),
109
- limit: 50,
110
- });
111
-
112
- // Persist a new body-weight entry (kilograms by default)
113
- await Health.saveSample({
114
- dataType: 'weight',
115
- value: 74.3,
116
- });
117
- ```
118
-
119
- ### Supported data types
120
-
121
- | Identifier | Default unit | Notes |
122
- | --------------- | ------------- | -------------------------- |
123
- | `steps` | `count` | Step count deltas |
124
- | `distance` | `meter` | Walking / running distance |
125
- | `calories` | `kilocalorie` | Active energy burned |
126
- | `totalCalories` | `kilocalorie` | Total energy burned |
127
- | `heartRate` | `bpm` | Beats per minute |
128
- | `weight` | `kilogram` | Body mass |
129
- | `height` | `meter` | Body height |
130
-
131
- All write operations expect the default unit shown above. On Android the `metadata` option is currently ignored by Health Connect.
132
-
133
- ### Workouts
134
-
135
- To query workout sessions, you need to request read permission for `'workouts'`:
136
-
137
- ```ts
138
- // Request permission to read workouts
139
- // IMPORTANT: To see totalEnergyBurned and totalDistance in workout data,
140
- // you MUST also request permissions for 'calories' (or 'totalCalories') and 'distance'
94
+ // Ask for read access to sleep and hydration data
141
95
  await Health.requestAuthorization({
142
- read: ['workouts', 'calories', 'totalCalories', 'distance'], // Include data types for workout metrics
143
- write: [],
96
+ read: ['sleep', 'hydration'],
144
97
  });
145
98
 
146
- // Query recent workouts
147
- const { workouts } = await Health.queryWorkouts({
99
+ // Query recent sleep sessions
100
+ const { sleepSessions } = await Health.querySleep({
148
101
  startDate: new Date(Date.now() - 7 * 24 * 60 * 60 * 1000).toISOString(),
149
102
  endDate: new Date().toISOString(),
150
103
  limit: 10,
151
104
  });
152
105
 
153
- // Each workout may include:
154
- // - workoutType, duration, startDate, endDate (always present)
155
- // - totalEnergyBurned (if calories/totalCalories permission granted and data exists)
156
- // - totalDistance (if distance permission granted and data exists)
106
+ // Query recent hydration records
107
+ const { hydrationRecords } = await Health.queryHydration({
108
+ startDate: new Date(Date.now() - 24 * 60 * 60 * 1000).toISOString(),
109
+ endDate: new Date().toISOString(),
110
+ limit: 50,
111
+ });
157
112
  ```
158
113
 
159
- **Note:**
160
-
161
- - `'workouts'` is a special read-only permission type. You cannot write workouts with this plugin.
162
- - Workout energy and distance data are aggregated from separate Health Connect records during the workout time period. If you don't request permissions for `calories`/`totalCalories` and `distance`, these fields will be missing from workout results.
163
- - If `totalEnergyBurned` or `totalDistance` are missing despite having permissions, it means no calorie or distance data was recorded during that workout period in Health Connect.
164
-
165
114
  ### Sleep
166
115
 
167
116
  To query sleep sessions, you need to request read permission for `'sleep'`:
@@ -208,6 +157,34 @@ const { sleepSessions } = await Health.querySleep({
208
157
  - `'sleep'` is a special read-only permission type. You cannot write sleep data with this plugin.
209
158
  - Not all sleep sessions include detailed sleep stages. Some apps may only record the overall sleep duration.
210
159
 
160
+ ### Hydration
161
+
162
+ To query hydration records, you need to request read permission for `'hydration'`:
163
+
164
+ ```ts
165
+ // Request permission to read hydration data
166
+ await Health.requestAuthorization({
167
+ read: ['hydration'],
168
+ write: [],
169
+ });
170
+
171
+ // Query recent hydration records
172
+ const { hydrationRecords } = await Health.queryHydration({
173
+ startDate: new Date(Date.now() - 24 * 60 * 60 * 1000).toISOString(),
174
+ endDate: new Date().toISOString(),
175
+ limit: 50,
176
+ });
177
+
178
+ // Each hydration record includes:
179
+ // - volume (in liters), startDate, endDate (always present)
180
+ // - sourceName, sourceId (source app information)
181
+ // - metadata (optional, client record information)
182
+ ```
183
+
184
+ **Note:**
185
+
186
+ - `'hydration'` is a special read-only permission type. You cannot write hydration data with this plugin.
187
+
211
188
  ## API
212
189
 
213
190
  <docgen-index>
@@ -215,12 +192,9 @@ const { sleepSessions } = await Health.querySleep({
215
192
  * [`isAvailable()`](#isavailable)
216
193
  * [`requestAuthorization(...)`](#requestauthorization)
217
194
  * [`checkAuthorization(...)`](#checkauthorization)
218
- * [`readSamples(...)`](#readsamples)
219
- * [`saveSample(...)`](#savesample)
220
195
  * [`getPluginVersion()`](#getpluginversion)
221
196
  * [`openHealthConnectSettings()`](#openhealthconnectsettings)
222
197
  * [`showPrivacyPolicy()`](#showprivacypolicy)
223
- * [`queryWorkouts(...)`](#queryworkouts)
224
198
  * [`querySleep(...)`](#querysleep)
225
199
  * [`queryHydration(...)`](#queryhydration)
226
200
  * [Interfaces](#interfaces)
@@ -250,7 +224,7 @@ Returns whether the current platform supports the native health SDK.
250
224
  requestAuthorization(options: AuthorizationOptions) => Promise<AuthorizationStatus>
251
225
  ```
252
226
 
253
- Requests read/write access to the provided data types.
227
+ Requests read access to the provided data types.
254
228
 
255
229
  | Param | Type |
256
230
  | ------------- | --------------------------------------------------------------------- |
@@ -278,38 +252,6 @@ Checks authorization status for the provided data types without prompting the us
278
252
  --------------------
279
253
 
280
254
 
281
- ### readSamples(...)
282
-
283
- ```typescript
284
- readSamples(options: QueryOptions) => Promise<ReadSamplesResult>
285
- ```
286
-
287
- Reads samples for the given data type within the specified time frame.
288
-
289
- | Param | Type |
290
- | ------------- | ----------------------------------------------------- |
291
- | **`options`** | <code><a href="#queryoptions">QueryOptions</a></code> |
292
-
293
- **Returns:** <code>Promise&lt;<a href="#readsamplesresult">ReadSamplesResult</a>&gt;</code>
294
-
295
- --------------------
296
-
297
-
298
- ### saveSample(...)
299
-
300
- ```typescript
301
- saveSample(options: WriteSampleOptions) => Promise<void>
302
- ```
303
-
304
- Writes a single sample to the native health store.
305
-
306
- | Param | Type |
307
- | ------------- | ----------------------------------------------------------------- |
308
- | **`options`** | <code><a href="#writesampleoptions">WriteSampleOptions</a></code> |
309
-
310
- --------------------
311
-
312
-
313
255
  ### getPluginVersion()
314
256
 
315
257
  ```typescript
@@ -355,23 +297,6 @@ or by placing an HTML file at www/privacypolicy.html in your assets.
355
297
  --------------------
356
298
 
357
299
 
358
- ### queryWorkouts(...)
359
-
360
- ```typescript
361
- queryWorkouts(options: QueryWorkoutsOptions) => Promise<QueryWorkoutsResult>
362
- ```
363
-
364
- Queries workout sessions from the native health store on Android (Health Connect).
365
-
366
- | Param | Type | Description |
367
- | ------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------------------------- |
368
- | **`options`** | <code><a href="#queryworkoutsoptions">QueryWorkoutsOptions</a></code> | Query options including optional workout type filter, date range, limit, and sort order |
369
-
370
- **Returns:** <code>Promise&lt;<a href="#queryworkoutsresult">QueryWorkoutsResult</a>&gt;</code>
371
-
372
- --------------------
373
-
374
-
375
300
  ### querySleep(...)
376
301
 
377
302
  ```typescript
@@ -420,96 +345,19 @@ Queries hydration records from the native health store on Android (Health Connec
420
345
 
421
346
  #### AuthorizationStatus
422
347
 
423
- | Prop | Type | Description |
424
- | --------------------- | ------------------------------------ | ----------------------------------------------------------- |
425
- | **`readAuthorized`** | <code>ReadAuthorizationType[]</code> | Data types (and 'workouts') that are authorized for reading |
426
- | **`readDenied`** | <code>ReadAuthorizationType[]</code> | Data types (and 'workouts') that are denied for reading |
427
- | **`writeAuthorized`** | <code>HealthDataType[]</code> | Data types that are authorized for writing |
428
- | **`writeDenied`** | <code>HealthDataType[]</code> | Data types that are denied for writing |
348
+ | Prop | Type | Description |
349
+ | --------------------- | ------------------------------------ | ------------------------------------------ |
350
+ | **`readAuthorized`** | <code>ReadAuthorizationType[]</code> | Data types that are authorized for reading |
351
+ | **`readDenied`** | <code>ReadAuthorizationType[]</code> | Data types that are denied for reading |
352
+ | **`writeAuthorized`** | <code>never[]</code> | Data types that are authorized for writing |
353
+ | **`writeDenied`** | <code>never[]</code> | Data types that are denied for writing |
429
354
 
430
355
 
431
356
  #### AuthorizationOptions
432
357
 
433
- | Prop | Type | Description |
434
- | ----------- | ------------------------------------ | ------------------------------------------------------------------------------------------------------------ |
435
- | **`read`** | <code>ReadAuthorizationType[]</code> | Data types that should be readable after authorization. Include 'workouts' to enable queryWorkouts() method. |
436
- | **`write`** | <code>HealthDataType[]</code> | Data types that should be writable after authorization. |
437
-
438
-
439
- #### ReadSamplesResult
440
-
441
- | Prop | Type |
442
- | ------------- | --------------------------- |
443
- | **`samples`** | <code>HealthSample[]</code> |
444
-
445
-
446
- #### HealthSample
447
-
448
- | Prop | Type |
449
- | ---------------- | --------------------------------------------------------- |
450
- | **`dataType`** | <code><a href="#healthdatatype">HealthDataType</a></code> |
451
- | **`value`** | <code>number</code> |
452
- | **`unit`** | <code><a href="#healthunit">HealthUnit</a></code> |
453
- | **`startDate`** | <code>string</code> |
454
- | **`endDate`** | <code>string</code> |
455
- | **`sourceName`** | <code>string</code> |
456
- | **`sourceId`** | <code>string</code> |
457
-
458
-
459
- #### QueryOptions
460
-
461
- | Prop | Type | Description |
462
- | --------------- | --------------------------------------------------------- | ------------------------------------------------------------------ |
463
- | **`dataType`** | <code><a href="#healthdatatype">HealthDataType</a></code> | The type of data to retrieve from the health store. |
464
- | **`startDate`** | <code>string</code> | Inclusive ISO 8601 start date (defaults to now - 1 day). |
465
- | **`endDate`** | <code>string</code> | Exclusive ISO 8601 end date (defaults to now). |
466
- | **`limit`** | <code>number</code> | Maximum number of samples to return (defaults to 100). |
467
- | **`ascending`** | <code>boolean</code> | Return results sorted ascending by start date (defaults to false). |
468
-
469
-
470
- #### WriteSampleOptions
471
-
472
- | Prop | Type | Description |
473
- | --------------- | --------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
474
- | **`dataType`** | <code><a href="#healthdatatype">HealthDataType</a></code> | |
475
- | **`value`** | <code>number</code> | |
476
- | **`unit`** | <code><a href="#healthunit">HealthUnit</a></code> | Optional unit override. If omitted, the default unit for the data type is used (count for `steps`, meter for `distance`, kilocalorie for `calories` and `totalCalories`, bpm for `heartRate`, kilogram for `weight`, meter for `height`). |
477
- | **`startDate`** | <code>string</code> | ISO 8601 start date for the sample. Defaults to now. |
478
- | **`endDate`** | <code>string</code> | ISO 8601 end date for the sample. Defaults to startDate. |
479
- | **`metadata`** | <code><a href="#record">Record</a>&lt;string, string&gt;</code> | Metadata key-value pairs forwarded to the native APIs where supported. |
480
-
481
-
482
- #### QueryWorkoutsResult
483
-
484
- | Prop | Type |
485
- | -------------- | ---------------------- |
486
- | **`workouts`** | <code>Workout[]</code> |
487
-
488
-
489
- #### Workout
490
-
491
- | Prop | Type | Description |
492
- | ----------------------- | --------------------------------------------------------------- | --------------------------------------------------- |
493
- | **`workoutType`** | <code><a href="#workouttype">WorkoutType</a></code> | The type of workout. |
494
- | **`duration`** | <code>number</code> | Duration of the workout in seconds. |
495
- | **`totalEnergyBurned`** | <code>number</code> | Total energy burned in kilocalories (if available). |
496
- | **`totalDistance`** | <code>number</code> | Total distance in meters (if available). |
497
- | **`startDate`** | <code>string</code> | ISO 8601 start date of the workout. |
498
- | **`endDate`** | <code>string</code> | ISO 8601 end date of the workout. |
499
- | **`sourceName`** | <code>string</code> | Source name that recorded the workout. |
500
- | **`sourceId`** | <code>string</code> | Source bundle identifier. |
501
- | **`metadata`** | <code><a href="#record">Record</a>&lt;string, string&gt;</code> | Additional metadata (if available). |
502
-
503
-
504
- #### QueryWorkoutsOptions
505
-
506
- | Prop | Type | Description |
507
- | ----------------- | --------------------------------------------------- | ------------------------------------------------------------------------- |
508
- | **`workoutType`** | <code><a href="#workouttype">WorkoutType</a></code> | Optional workout type filter. If omitted, all workout types are returned. |
509
- | **`startDate`** | <code>string</code> | Inclusive ISO 8601 start date (defaults to now - 1 day). |
510
- | **`endDate`** | <code>string</code> | Exclusive ISO 8601 end date (defaults to now). |
511
- | **`limit`** | <code>number</code> | Maximum number of workouts to return (defaults to 100). |
512
- | **`ascending`** | <code>boolean</code> | Return results sorted ascending by start date (defaults to false). |
358
+ | Prop | Type | Description |
359
+ | ---------- | ------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------- |
360
+ | **`read`** | <code>ReadAuthorizationType[]</code> | Data types that should be readable after authorization. Include 'sleep' to enable querySleep() method. Include 'hydration' to enable queryHydration() method. |
513
361
 
514
362
 
515
363
  #### QuerySleepResult
@@ -587,21 +435,15 @@ Queries hydration records from the native health store on Android (Health Connec
587
435
  #### ReadAuthorizationType
588
436
 
589
437
  Data types that can be requested for read authorization.
590
- Includes 'workouts' for querying workout sessions via queryWorkouts().
591
438
  Includes 'sleep' for querying sleep sessions via querySleep().
592
439
  Includes 'hydration' for querying hydration records via queryHydration().
593
440
 
594
- <code><a href="#healthdatatype">HealthDataType</a> | 'workouts' | 'sleep' | 'hydration'</code>
441
+ <code>'sleep' | 'hydration'</code>
595
442
 
596
443
 
597
- #### HealthDataType
598
-
599
- <code>'steps' | 'distance' | 'calories' | 'totalCalories' | 'heartRate' | 'weight' | 'height'</code>
600
-
601
-
602
- #### HealthUnit
444
+ #### SleepStage
603
445
 
604
- <code>'count' | 'meter' | 'kilocalorie' | 'bpm' | 'kilogram'</code>
446
+ <code>'unknown' | 'awake' | 'sleeping' | 'outOfBed' | 'awakeInBed' | 'light' | 'deep' | 'rem'</code>
605
447
 
606
448
 
607
449
  #### Record
@@ -610,16 +452,6 @@ Construct a type with a set of properties K of type T
610
452
 
611
453
  <code>{
612
454
  [P in K]: T;
613
455
  }</code>
614
456
 
615
-
616
- #### WorkoutType
617
-
618
- <code>'running' | 'cycling' | 'walking' | 'swimming' | 'yoga' | 'strengthTraining' | 'hiking' | 'tennis' | 'basketball' | 'soccer' | 'americanFootball' | 'baseball' | 'crossTraining' | 'elliptical' | 'rowing' | 'stairClimbing' | 'traditionalStrengthTraining' | 'waterFitness' | 'waterPolo' | 'waterSports' | 'wrestling' | 'other'</code>
619
-
620
-
621
- #### SleepStage
622
-
623
- <code>'unknown' | 'awake' | 'sleeping' | 'outOfBed' | 'awakeInBed' | 'light' | 'deep' | 'rem'</code>
624
-
625
457
  </docgen-api>
626
458
 
627
459
  ### Credits: