### Install Dependencies
Source: https://github.com/mley/capacitor-health/blob/main/CONTRIBUTING.md
Run this command to install project dependencies after cloning the repository.
```shell
npm install
```
--------------------------------
### Install Capacitor Health Plugin
Source: https://github.com/mley/capacitor-health/blob/main/README.md
Install the plugin using npm and sync with Capacitor. Ensure you have the necessary build tools configured.
```bash
npm install capacitor-health
npx cap sync
```
--------------------------------
### Install SwiftLint (macOS)
Source: https://github.com/mley/capacitor-health/blob/main/CONTRIBUTING.md
If you are on macOS, install SwiftLint using Homebrew to enforce Swift code style.
```shell
brew install swiftlint
```
--------------------------------
### Install capacitor-health Plugin
Source: https://context7.com/mley/capacitor-health/llms.txt
Install the plugin using npm and sync with Capacitor. For iOS, configure Info.plist. For Android, add necessary permissions and activities to AndroidManifest.xml.
```bash
npm install capacitor-health
npx cap sync
```
```xml
```
--------------------------------
### Check Health Availability
Source: https://context7.com/mley/capacitor-health/llms.txt
Verify if the health platform is accessible. On Android, this checks for Google Health Connect installation and prompts the user to install it if unavailable. This must be called before other API methods on Android.
```typescript
import { Health } from 'capacitor-health';
async function checkAvailability() {
const { available } = await Health.isHealthAvailable();
if (!available) {
// Android: prompt user to install Health Connect
await Health.showHealthConnectInPlayStore();
return;
}
console.log('Health API is available');
// Expected: "Health API is available"
}
```
--------------------------------
### Show Health Connect in Play Store
Source: https://github.com/mley/capacitor-health/blob/main/README.md
Opens the Google Health Connect app listing in the Play Store, allowing users to install or update it.
```typescript
showHealthConnectInPlayStore() => Promise
```
--------------------------------
### isHealthAvailable()
Source: https://context7.com/mley/capacitor-health/llms.txt
Checks if the health platform is accessible on the current device. On Android, it returns false if Google Health Connect is not installed. This method must be called before any other API method on Android to initialize the HealthConnectClient.
```APIDOC
## isHealthAvailable()
### Description
Checks whether the health platform is accessible on the current device. On Android, returns `false` if Google Health Connect is not installed. Must be called before any other API method on Android to initialize the `HealthConnectClient`.
### Method
`Health.isHealthAvailable()`
### Parameters
None
### Response
- **available** (boolean) - Indicates if the health platform is available.
### Request Example
```typescript
import { Health } from 'capacitor-health';
async function checkAvailability() {
const { available } = await Health.isHealthAvailable();
if (!available) {
// Android: prompt user to install Health Connect
await Health.showHealthConnectInPlayStore();
return;
}
console.log('Health API is available');
}
```
### Response Example
```json
{
"available": true
}
```
```
--------------------------------
### isHealthAvailable
Source: https://github.com/mley/capacitor-health/blob/main/README.md
Checks if the health API is available on the device. On Android, if false is returned, it suggests the Google Health Connect app might not be installed.
```APIDOC
## isHealthAvailable()
### Description
Checks if health API is available.
Android: If false is returned, the Google Health Connect app is probably not installed. See showHealthConnectInPlayStore()
### Method
```typescript
isHealthAvailable() => Promise<{ available: boolean; }>
```
### Response
#### Success Response (200)
- **available** (boolean) - Indicates if the health API is available.
```
--------------------------------
### Check Health API Availability
Source: https://github.com/mley/capacitor-health/blob/main/README.md
Use this method to determine if the health API is available on the device. On Android, a false return value may indicate that the Google Health Connect app is not installed.
```typescript
isHealthAvailable() => Promise<{ available: boolean; }>
```
--------------------------------
### Build Plugin and Docs
Source: https://github.com/mley/capacitor-health/blob/main/CONTRIBUTING.md
Compiles TypeScript to ESM JavaScript and bundles it for use in applications. Also generates API documentation.
```shell
npm run build
```
--------------------------------
### Verify Web and Native Projects
Source: https://github.com/mley/capacitor-health/blob/main/CONTRIBUTING.md
Builds and validates both the web and native parts of the plugin. Useful for CI checks.
```shell
npm run verify
```
--------------------------------
### Publish Plugin
Source: https://github.com/mley/capacitor-health/blob/main/CONTRIBUTING.md
Publishes the plugin to npm. A pre-publish hook ensures the plugin is prepared before publishing.
```shell
npm publish
```
--------------------------------
### Open iOS Settings
Source: https://context7.com/mley/capacitor-health/llms.txt
Opens the app's system Settings page on iOS. Note that Health permissions are not deep-linked directly.
```typescript
import { Health } from 'capacitor-health';
import { Capacitor } from '@capacitor/core';
async function openSettings() {
if (Capacitor.getPlatform() === 'ios') {
await Health.openAppleHealthSettings();
// User is taken to the app's system Settings page
}
}
```
--------------------------------
### Query Workouts with Details
Source: https://context7.com/mley/capacitor-health/llms.txt
Retrieves workout sessions within a date range, including heart rate and GPS data. Ensure the necessary permissions are granted before calling.
```typescript
import { Health, Workout } from 'capacitor-health';
async function fetchRecentWorkouts() {
const startDate = new Date();
startDate.setDate(startDate.getDate() - 30);
const { workouts } = await Health.queryWorkouts({
startDate: startDate.toISOString(),
endDate: new Date().toISOString(),
includeHeartRate: true,
includeRoute: true,
includeSteps: false,
});
workouts.forEach((workout: Workout) => {
const durationMin = Math.round(workout.duration / 60);
console.log(`[${workout.workoutType}] ${durationMin} min | ${workout.calories} kcal | ${workout.distance ?? 0} m`);
console.log(` Source: ${workout.sourceName} (${workout.sourceBundleId})`);
if (workout.heartRate && workout.heartRate.length > 0) {
const avgBpm =
workout.heartRate.reduce((sum, s) => sum + s.bpm, 0) / workout.heartRate.length;
console.log(` Avg HR: ${avgBpm.toFixed(0)} bpm over ${workout.heartRate.length} samples`);
}
if (workout.route && workout.route.length > 0) {
console.log(` Route: ${workout.route.length} GPS points`);
console.log(` First point: lat=${workout.route[0].lat}, lng=${workout.route[0].lng}`);
}
});
/*
Expected output:
[RUNNING] 42 min | 380 kcal | 6850 m
Source: Strava (com.strava)
Avg HR: 158 bpm over 2520 samples
Route: 841 GPS points
First point: lat=48.8566, lng=2.3522
*/
}
```
--------------------------------
### queryWorkouts
Source: https://github.com/mley/capacitor-health/blob/main/README.md
Queries workout data based on the provided request parameters.
```APIDOC
## queryWorkouts(request: QueryWorkoutRequest)
### Description
Queries workout data based on the specified request parameters.
### Method
```typescript
queryWorkouts(request: QueryWorkoutRequest) => Promise
```
### Parameters
#### Path Parameters
- **`request`** (QueryWorkoutRequest) - Required - The request object for querying workouts.
```
--------------------------------
### Query Workouts
Source: https://github.com/mley/capacitor-health/blob/main/README.md
Queries workout data based on the provided request parameters.
```typescript
queryWorkouts(request: QueryWorkoutRequest) => Promise
```
--------------------------------
### Open Health Connect Settings
Source: https://github.com/mley/capacitor-health/blob/main/README.md
Opens the Google Health Connect app to manage health data permissions and settings.
```typescript
openHealthConnectSettings() => Promise
```
--------------------------------
### openHealthConnectSettings
Source: https://context7.com/mley/capacitor-health/llms.txt
Opens the Google Health Connect app directly, allowing the user to manually review and adjust permissions. Use this when `checkHealthPermissions` reveals a denied permission that can no longer be re-requested programmatically.
```APIDOC
## openHealthConnectSettings()
### Description
Opens the Google Health Connect app directly on Android devices. This allows users to manually review and adjust their health data permissions, especially useful when programmatic re-requests are not possible.
### Method
`openHealthConnectSettings`
### Parameters
None
### Request Example
```typescript
await Health.openHealthConnectSettings();
```
### Response
None. This method triggers a system-level navigation to the Health Connect app.
```
--------------------------------
### RouteSample Data Structure
Source: https://github.com/mley/capacitor-health/blob/main/README.md
Defines the structure for a single point in a workout route, including timestamp, latitude, longitude, and altitude.
```APIDOC
## RouteSample
### Description
Represents a geographical point recorded during a workout route.
### Properties
- **`timestamp`** (string) - The date and time when the route sample was recorded.
- **`lat`** (number) - The latitude of the location.
- **`lng`** (number) - The longitude of the location.
- **`alt`** (number) - The altitude of the location in meters.
```
--------------------------------
### Lint and Format Code
Source: https://github.com/mley/capacitor-health/blob/main/CONTRIBUTING.md
Checks code quality and formatting, with auto-formatting capabilities. Integrates ESLint, Prettier, and SwiftLint.
```shell
npm run lint
```
```shell
npm run fmt
```
--------------------------------
### openHealthConnectSettings
Source: https://github.com/mley/capacitor-health/blob/main/README.md
Opens the Google Health Connect app, allowing users to manage their health data permissions and settings.
```APIDOC
## openHealthConnectSettings()
### Description
Opens the Google Health Connect application to manage health data settings.
### Method
```typescript
openHealthConnectSettings() => Promise
```
```
--------------------------------
### Register Health Plugin
Source: https://context7.com/mley/capacitor-health/llms.txt
Import the Health object from 'capacitor-health' to access its methods. This is the primary way to interact with the plugin's API.
```typescript
import { Health } from 'capacitor-health';
// All methods are called on the Health object, e.g. Health.isHealthAvailable()
```
--------------------------------
### Open Health Connect Settings (Android)
Source: https://context7.com/mley/capacitor-health/llms.txt
Opens the Google Health Connect app directly on Android. Use when permissions cannot be re-requested programmatically.
```typescript
import { Health } from 'capacitor-health';
import { Capacitor } from '@capacitor/core';
async function openHealthConnect() {
if (Capacitor.getPlatform() === 'android') {
await Health.openHealthConnectSettings();
}
}
```
--------------------------------
### Android Manifest Configuration for Health Connect Permissions
Source: https://github.com/mley/capacitor-health/blob/main/README.md
Configure the Android Manifest to handle Health Connect permissions, including activities for showing permission rationale for different Android versions.
```xml
```
--------------------------------
### openAppleHealthSettings
Source: https://github.com/mley/capacitor-health/blob/main/README.md
Opens the Apple Health settings screen. Note that direct access to app-specific health permissions within settings is not possible.
```APIDOC
## openAppleHealthSettings()
### Description
Opens the main Apple Health settings screen. Direct navigation to app-specific permission settings is not supported.
### Method
```typescript
openAppleHealthSettings() => Promise
```
```
--------------------------------
### QueryWorkoutRequest Structure
Source: https://github.com/mley/capacitor-health/blob/main/README.md
Defines the parameters for requesting workout data, allowing filtering by date range and inclusion of heart rate and route data.
```APIDOC
## QueryWorkoutRequest
### Description
Specifies the criteria for querying workout data.
### Properties
- **`startDate`** (string) - The start date for the query range.
- **`endDate`** (string) - The end date for the query range.
- **`includeHeartRate`** (boolean) - Whether to include heart rate data in the response. Defaults to false.
- **`includeRoute`** (boolean) - Whether to include route data in the response. Defaults to false.
```
--------------------------------
### Open Apple Health Settings
Source: https://github.com/mley/capacitor-health/blob/main/README.md
Opens the app's settings related to Apple Health. Direct navigation to specific permission configurations within the Settings app is not possible.
```typescript
openAppleHealthSettings() => Promise
```
--------------------------------
### showHealthConnectInPlayStore
Source: https://github.com/mley/capacitor-health/blob/main/README.md
Opens the Google Health Connect app listing in the Google Play Store.
```APIDOC
## showHealthConnectInPlayStore()
### Description
Opens the Google Health Connect app in the Google Play Store.
### Method
```typescript
showHealthConnectInPlayStore() => Promise
```
```
--------------------------------
### Workout Data Structure
Source: https://github.com/mley/capacitor-health/blob/main/README.md
Defines the properties of a workout record, including duration, distance, calories, and associated route and heart rate data.
```APIDOC
## Workout
### Description
Represents a single workout session with details like start and end times, type, source, duration, distance, and calories burned. It can also include associated route and heart rate samples.
### Properties
- **`startDate`** (string) - The start date and time of the workout.
- **`endDate`** (string) - The end date and time of the workout.
- **`workoutType`** (string) - The type of workout (e.g., running, cycling).
- **`sourceName`** (string) - The name of the application or device that recorded the workout.
- **`id`** (string) - A unique identifier for the workout.
- **`duration`** (number) - The total duration of the workout in seconds.
- **`distance`** (number) - The total distance covered during the workout in meters.
- **`calories`** (number) - The estimated number of calories burned during the workout.
- **`sourceBundleId`** (string) - The bundle identifier of the source application.
- **`route`** (RouteSample[]) - An array of route samples, if available.
- **`heartRate`** (HeartRateSample[]) - An array of heart rate samples, if available.
```
--------------------------------
### requestHealthPermissions(permissions)
Source: https://context7.com/mley/capacitor-health/llms.txt
Prompts the user to grant the specified health permissions. On iOS, it silently returns without prompting if permissions were already resolved. On Android, the system dialog is shown, and apps may only prompt a limited number of times before the user must grant access manually.
```APIDOC
## requestHealthPermissions(permissions)
### Description
Prompts the user to grant the specified health permissions. On iOS, silently returns without prompting if permissions were already resolved; the return value assumes all permissions were granted since iOS does not expose the actual grant status. On Android, the system dialog is shown; apps may only prompt a limited number of times before the user must grant access manually.
### Method
`Health.requestHealthPermissions(options)`
### Parameters
#### Request Body
- **permissions** (HealthPermission[]) - Required - An array of health permissions to request.
### Request Example
```typescript
import { Health, HealthPermission } from 'capacitor-health';
async function requestPermissions() {
const permissionsToRequest: HealthPermission[] = [
'READ_STEPS',
'READ_WORKOUTS',
'READ_HEART_RATE',
'READ_ROUTE',
'READ_ACTIVE_CALORIES',
'READ_DISTANCE',
'READ_MINDFULNESS',
];
try {
const response = await Health.requestHealthPermissions({
permissions: permissionsToRequest,
});
// response.permissions is { [permissionName]: boolean }
console.log('Granted:', response.permissions);
} catch (err) {
console.error('Permission request failed:', err);
}
}
```
### Response
#### Success Response
- **permissions** ({ [permissionName: string]: boolean }) - An object where keys are permission names and values indicate if the permission was granted.
### Response Example
```json
{
"permissions": {
"READ_STEPS": true,
"READ_WORKOUTS": true,
"READ_HEART_RATE": true,
"READ_ROUTE": true,
"READ_ACTIVE_CALORIES": true,
"READ_DISTANCE": true,
"READ_MINDFULNESS": true
}
}
```
```
--------------------------------
### Android Manifest Queries and Permissions for Health Data
Source: https://github.com/mley/capacitor-health/blob/main/README.md
Declare necessary queries for the Health Connect package and request permissions for reading specific health data types in the Android Manifest.
```xml
```
--------------------------------
### TypeScript Types Reference
Source: https://context7.com/mley/capacitor-health/llms.txt
Reference for the TypeScript types used within the capacitor-health plugin, including permissions, workout data, and health records.
```typescript
// Available permission identifiers
type HealthPermission =
| 'READ_STEPS'
| 'READ_WORKOUTS'
| 'READ_ACTIVE_CALORIES'
| 'READ_TOTAL_CALORIES'
| 'READ_DISTANCE'
| 'READ_HEART_RATE'
| 'READ_ROUTE'
| 'READ_MINDFULNESS';
interface AggregatedSample {
startDate: string; // ISO 8601
endDate: string; // ISO 8601
value: number; // unit depends on dataType: count / kcal / seconds
}
interface Workout {
id?: string;
startDate: string;
endDate: string;
workoutType: string; // platform-specific string
sourceName: string;
sourceBundleId: string;
duration: number; // seconds
calories: number; // kcal
distance?: number; // meters
steps?: number;
heartRate?: HeartRateSample[];
route?: RouteSample[];
}
interface HeartRateSample {
timestamp: string; // ISO 8601
bpm: number;
}
interface RouteSample {
timestamp: string; // ISO 8601
lat: number;
lng: number;
alt?: number; // meters
}
interface HealthRecord { // Android only
startDate: string;
endDate: string;
value: number;
sourceBundleId: string;
}
```
--------------------------------
### Check Health Permissions (Android)
Source: https://context7.com/mley/capacitor-health/llms.txt
Queries Health Connect for permission status without UI. Rejects on iOS. Use to verify granted permissions before data access.
```typescript
import { Health } from 'capacitor-health';
async function verifyPermissions() {
try {
const { permissions } = await Health.checkHealthPermissions({
permissions: ['READ_STEPS', 'READ_ACTIVE_CALORIES', 'READ_DISTANCE'],
});
// permissions is a { [key: string]: boolean }[] – one object per permission
const stepsGranted = permissions['READ_STEPS'];
if (!stepsGranted) {
console.warn('Steps permission not granted – redirect to Health Connect settings');
await Health.openHealthConnectSettings();
} else {
console.log('All required permissions granted');
}
} catch (err) {
// Throws on iOS – guard with platform check
console.error('checkHealthPermissions error:', err);
}
}
```
--------------------------------
### queryAggregated
Source: https://context7.com/mley/capacitor-health/llms.txt
Returns bucketed aggregate health data for a date range. Supported `dataType` values are 'steps', 'active-calories', and 'mindfulness'. The supported `bucket` on Android is 'day'; iOS additionally supports 'hour' and 'week'. The optional `dataOrigins` array (Android only) restricts aggregation to specific app package names.
```APIDOC
## queryAggregated(request)
### Description
Retrieves aggregated health data within a specified date range, categorized into buckets. This method allows fetching data like steps, active calories, and mindfulness, with platform-specific options for data types and bucketing granularity.
### Method
`queryAggregated`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
* **startDate** (string) - Required - The start date for the data range in ISO 8601 format.
* **endDate** (string) - Required - The end date for the data range in ISO 8601 format.
* **dataType** (string) - Required - The type of health data to query. Supported values: 'steps', 'active-calories', 'mindfulness'.
* **bucket** (string) - Required - The time granularity for the aggregated data. Supported values: 'day' (Android only), 'hour' (iOS only), 'week' (iOS only).
* **dataOrigins** (string[]) - Optional (Android only) - An array of package names to filter the data aggregation. iOS automatically de-duplicates sources and ignores this field.
### Request Example
```typescript
await Health.queryAggregated({
startDate: '2024-01-01T00:00:00.000Z',
endDate: '2024-01-08T00:00:00.000Z',
dataType: 'steps',
bucket: 'day',
dataOrigins: ['com.example.app'], // Android only
});
```
### Response
#### Success Response
- **aggregatedData** (Array<{ startDate: string, endDate: string, value: number | string }>)
- **startDate** (string) - The start timestamp of the bucket.
- **endDate** (string) - The end timestamp of the bucket.
- **value** (number | string) - The aggregated value for the bucket. Type depends on `dataType` (e.g., number for steps/calories, string for mindfulness).
```
--------------------------------
### HeartRateSample Data Structure
Source: https://github.com/mley/capacitor-health/blob/main/README.md
Defines the structure for a single heart rate reading, including timestamp and beats per minute (BPM).
```APIDOC
## HeartRateSample
### Description
Represents a single heart rate measurement.
### Properties
- **`timestamp`** (string) - The date and time when the heart rate was measured.
- **`bpm`** (number) - The heart rate in beats per minute.
```
--------------------------------
### Query Aggregated Health Data
Source: https://context7.com/mley/capacitor-health/llms.txt
Returns bucketed aggregate health data for a date range. Supported data types include steps, active calories, and mindfulness. Android supports 'day' buckets; iOS supports 'hour' and 'week'.
```typescript
import { Health } from 'capacitor-health';
async function fetchDailySteps() {
const startDate = new Date();
startDate.setDate(startDate.getDate() - 7); // last 7 days
const { aggregatedData } = await Health.queryAggregated({
startDate: startDate.toISOString(),
endDate: new Date().toISOString(),
dataType: 'steps',
bucket: 'day',
// Android only: restrict to a single source
dataOrigins: ['com.sec.android.app.shealth'],
});
aggregatedData.forEach(sample => {
console.log(`${sample.startDate} → ${sample.endDate}: ${sample.value} steps`);
});
/*
Expected output:
2024-01-15T00:00:00 → 2024-01-16T00:00:00: 9423 steps
2024-01-16T00:00:00 → 2024-01-17T00:00:00: 11087 steps
...
*/
}
async function fetchDailyCalories() {
const { aggregatedData } = await Health.queryAggregated({
startDate: '2024-01-01T00:00:00.000Z',
endDate: '2024-01-08T00:00:00.000Z',
dataType: 'active-calories',
bucket: 'day',
});
// Each sample.value is in kilocalories
console.log('Active calories per day:', aggregatedData.map(s => s.value));
}
async function fetchMindfulnessMinutes() {
const { aggregatedData } = await Health.queryAggregated({
startDate: '2024-01-01T00:00:00.000Z',
endDate: '2024-01-08T00:00:00.000Z',
dataType: 'mindfulness',
bucket: 'day',
});
// Each sample.value is total seconds of mindfulness for the day
aggregatedData.forEach(s => {
console.log(`Mindfulness: ${s.value / 60} minutes on ${s.startDate}`);
});
}
```
--------------------------------
### Request Health Permissions
Source: https://context7.com/mley/capacitor-health/llms.txt
Prompt the user to grant specific health data permissions. Note that on iOS, the return value assumes all permissions are granted, as the actual status is not exposed. On Android, the system dialog may have limited prompts.
```typescript
import { Health, HealthPermission } from 'capacitor-health';
async function requestPermissions() {
const permissionsToRequest: HealthPermission[] = [
'READ_STEPS',
'READ_WORKOUTS',
'READ_HEART_RATE',
'READ_ROUTE',
'READ_ACTIVE_CALORIES',
'READ_DISTANCE',
'READ_MINDFULNESS',
];
try {
const response = await Health.requestHealthPermissions({
permissions: permissionsToRequest,
});
// response.permissions is { [permissionName]: boolean }
console.log('Granted:', response.permissions);
// Expected: { READ_STEPS: true, READ_WORKOUTS: true, READ_HEART_RATE: true, ... }
} catch (err) {
console.error('Permission request failed:', err);
}
}
```
--------------------------------
### queryRecords
Source: https://context7.com/mley/capacitor-health/llms.txt
Returns individual health records for a specified data type, tagged with their originating app. This method is Android-only and currently only supports 'steps' data type.
```APIDOC
## queryRecords(request)
### Description
**Android only.** Returns individual (non-aggregated) health records for a data type, each tagged with its originating app's package name. This is useful for detecting and deduplicating data from multiple sources (e.g. Samsung Health and Google Fit both writing steps). Currently only supports `dataType: 'steps'`. On iOS, this method always rejects since Apple Health handles source de-duplication automatically.
### Method
```typescript
Health.queryRecords({
startDate: string,
endDate: string,
dataType: 'steps'
})
```
### Parameters
#### Request Body
- **startDate** (string) - Required - The start date for the query in ISO 8601 format.
- **endDate** (string) - Required - The end date for the query in ISO 8601 format.
- **dataType** (string) - Required - The type of data to query. Currently only supports `'steps'`.
### Response
#### Success Response (200)
- **records** (HealthRecord[]) - An array of health record objects.
### Request Example
```typescript
import { Health, HealthRecord } from 'capacitor-health';
import { Capacitor } from '@capacitor/core';
async function inspectStepSources() {
if (Capacitor.getPlatform() !== 'android') {
console.log('queryRecords is Android only');
return;
}
const { records } = await Health.queryRecords({
startDate: '2024-01-15T00:00:00.000Z',
endDate: '2024-01-16T00:00:00.000Z',
dataType: 'steps',
});
// Group step counts by source app
const bySource: Record = {};
records.forEach((record: HealthRecord) => {
bySource[record.sourceBundleId] = (bySource[record.sourceBundleId] ?? 0) + record.value;
});
console.log('Steps by source:', bySource);
// Identify the dominant source and exclude duplicates
const dominantSource = Object.entries(bySource).sort((a, b) => b[1] - a[1])[0];
console.log(`Using source: ${dominantSource[0]} (${dominantSource[1]} steps)`);
}
```
```
--------------------------------
### Request Health Permissions
Source: https://github.com/mley/capacitor-health/blob/main/README.md
Requests specific health permissions from the user. Note platform-specific behaviors for Android and iOS regarding permission granting and detection.
```typescript
requestHealthPermissions(permissions: PermissionsRequest) => Promise
```
--------------------------------
### Query Health Records (Android Only)
Source: https://context7.com/mley/capacitor-health/llms.txt
Retrieves individual health records for a specific data type, useful for deduplicating data from multiple sources. This method is Android-only.
```typescript
import { Health, HealthRecord } from 'capacitor-health';
import { Capacitor } from '@capacitor/core';
async function inspectStepSources() {
if (Capacitor.getPlatform() !== 'android') {
console.log('queryRecords is Android only');
return;
}
const { records } = await Health.queryRecords({
startDate: '2024-01-15T00:00:00.000Z',
endDate: '2024-01-16T00:00:00.000Z',
dataType: 'steps',
});
// Group step counts by source app
const bySource: Record = {};
records.forEach((record: HealthRecord) => {
bySource[record.sourceBundleId] = (bySource[record.sourceBundleId] ?? 0) + record.value;
});
console.log('Steps by source:', bySource);
/*
Expected output:
Steps by source: {
"com.sec.android.app.shealth": 7230,
"com.google.android.apps.fitness": 6980
}
*/
// Identify the dominant source and exclude duplicates
const dominantSource = Object.entries(bySource).sort((a, b) => b[1] - a[1])[0];
console.log(`Using source: ${dominantSource[0]} (${dominantSource[1]} steps)`);
}
```
--------------------------------
### HealthPermission Enum
Source: https://github.com/mley/capacitor-health/blob/main/README.md
Lists the types of health data that can be requested for read access.
```APIDOC
## HealthPermission
### Description
An enumeration of permissions that can be requested to read specific types of health data.
### Values
- **`'READ_STEPS'`**: Permission to read step count data.
- **`'READ_WORKOUTS'`**: Permission to read workout data.
- **`'READ_CALORIES'`**: Permission to read calorie data.
- **`'READ_DISTANCE'`**: Permission to read distance data.
- **`'READ_HEART_RATE'`**: Permission to read heart rate data.
- **`'READ_ROUTE'`**: Permission to read workout route data.
```
--------------------------------
### requestHealthPermissions
Source: https://github.com/mley/capacitor-health/blob/main/README.md
Requests health permissions from the user. Behavior differs between Android and iOS regarding permission handling and user feedback.
```APIDOC
## requestHealthPermissions(permissions: PermissionsRequest)
### Description
Requests the specified health permissions from the user.
### Method
```typescript
requestHealthPermissions(permissions: PermissionsRequest) => Promise
```
### Parameters
#### Path Parameters
- **`permissions`** (PermissionsRequest) - Required - The set of permissions to request from the user.
```
--------------------------------
### checkHealthPermissions
Source: https://context7.com/mley/capacitor-health/llms.txt
Queries the Health Connect permission controller on Android to determine the grant status for requested permissions without showing any UI. This method is not implemented on iOS and will reject.
```APIDOC
## checkHealthPermissions(permissions)
### Description
Queries the Health Connect permission controller to determine the current grant status for each requested permission without showing any UI. On Android, this method checks permissions without UI. On iOS, this method is not implemented and will reject.
### Method
`checkHealthPermissions`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
* **permissions** (string[]) - Required - An array of health data permissions to check (e.g., ['READ_STEPS', 'READ_ACTIVE_CALORIES']).
### Request Example
```typescript
await Health.checkHealthPermissions({
permissions: ['READ_STEPS', 'READ_ACTIVE_CALORIES', 'READ_DISTANCE'],
});
```
### Response
#### Success Response
- **permissions** ({ [key: string]: boolean }[]) - An array of objects, where each object maps a permission string to its boolean grant status.
```
--------------------------------
### Check Health Permissions on Android
Source: https://github.com/mley/capacitor-health/blob/main/README.md
On Android, this function checks the granted status for a given set of health permissions. It returns a `PermissionResponse` object detailing the status for each requested permission.
```typescript
checkHealthPermissions(permissions: PermissionsRequest) => Promise
```
--------------------------------
### checkHealthPermissions
Source: https://github.com/mley/capacitor-health/blob/main/README.md
Android only: Checks the granted status for a given set of health permissions.
```APIDOC
## checkHealthPermissions(...)
### Description
Android only: Returns for each given permission, if it was granted by the underlying health API.
### Method
```typescript
checkHealthPermissions(permissions: PermissionsRequest) => Promise
```
### Parameters
#### Request Body
- **permissions** (PermissionsRequest) - Required - The permissions to query.
### Response
#### Success Response (200)
- **PermissionResponse** - The response contains the status of the requested permissions.
```
--------------------------------
### queryAggregated
Source: https://github.com/mley/capacitor-health/blob/main/README.md
Queries aggregated health data within a specified date range and data type.
```APIDOC
## queryAggregated(request: QueryAggregatedRequest)
### Description
Queries aggregated health data such as steps or calories within a specified date range and bucket.
### Method
```typescript
queryAggregated(request: QueryAggregatedRequest) => Promise
```
### Parameters
#### Path Parameters
- **`request`** (QueryAggregatedRequest) - Required - The request object containing date range, data type, and bucket.
```
--------------------------------
### Query Aggregated Health Data
Source: https://github.com/mley/capacitor-health/blob/main/README.md
Queries aggregated health data based on specified date ranges, data types, and bucketing.
```typescript
queryAggregated(request: QueryAggregatedRequest) => Promise
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.