@capgo/capacitor-health

中文文档
8.12.1发布于 2026/11/09MPL-2.0TypeScriptESM + CJS零依赖构建来源已验证近 30 天下载 20.5万

Capacitor plugin to interact with data from Apple HealthKit and Health Connect

原始使用文档
文档目录27 节
  1. ➡️ Get started for free
  2. Key features
  3. Why Capacitor Health?
  4. Documentation
  5. Compatibility
  6. Install
  7. iOS Setup
  8. Android Setup
  9. Privacy Policy Setup
  10. Usage
  11. Supported data types
  12. Reading data older than 30 days (Android)
  13. New Data Types Examples
  14. Aggregated Queries
  15. API
  16. isAvailable()
  17. requestAuthorization(...)
  18. checkAuthorization(...)
  19. readSamples(...)
  20. saveSample(...)
  21. getPluginVersion()
  22. openHealthConnectSettings()
  23. showPrivacyPolicy()
  24. queryWorkouts(...)
  25. queryAggregated(...)
  26. Interfaces
  27. Type Aliases

@capgo/capacitor-health

Read and write health data with Apple HealthKit on iOS and Health Connect on Android through one API. Build fitness, wellness and medical apps once.

Capgo - Build Capacitor apps with AI, ship updates instantly

Capgo: push fixes to your Capacitor users in minutes, build signed iOS and Android apps without a Mac, and roll back in one click.

➡️ Get started for free

14-day unlimited free trial. No credit card required

🤖 Building with an AI coding agent? Install Capgo skills so Claude Code, Codex, Cursor, Copilot, or Gemini CLI know how to install and use @capgo/capacitor-health in your Capacitor app: npx skills add Cap-go/capgo-skills. Then ask your agent: "Add @capgo/capacitor-health to my Capacitor app and wire it up." Agent setup guides · Hosted MCP

@capgo/capacitor-health for Capacitor apps

Key features

  • Read samples: readSamples() for steps, heart rate, sleep and other types over a time range.
  • Write samples: saveSample() stores a single sample.
  • Workouts and aggregates: queryWorkouts() and queryAggregated() for summaries.
  • Authorization: requestAuthorization() and checkAuthorization() per data type.
  • Health Connect helpers: openHealthConnectSettings() and showPrivacyPolicy() on Android.
  • Platforms: iOS and Android. A few data types and units differ between iOS and Android, see the Supported data types table below. Not available on web.

Why Capacitor Health?

The only free, unified health data plugin for Capacitor supporting the latest native APIs:

  • Health Connect (Android) - Uses Google's newest health platform (replaces deprecated Google Fit)
  • HealthKit (iOS) - Full integration with Apple's health framework
  • Unified API - Same TypeScript interface across platforms with consistent units
  • Multiple metrics - Steps, distance, calories, heart rate, weight
  • Read & Write - Query historical data and save new health entries
  • Modern standards - Supports Android 8.0+ and iOS 14+
  • Modern package management - Supports both Swift Package Manager (SPM) and CocoaPods (SPM-ready for Capacitor 8)

Perfect for fitness apps, health trackers, wellness platforms, and medical applications.

Documentation

The most complete doc is available here: https://capgo.app/docs/plugins/health/

Compatibility

Plugin versionCapacitor compatibilityMaintained
v8.*.*v8.*.*✅
v7.*.*v7.*.*On demand
v6.*.*v6.*.*❌
v5.*.*v5.*.*❌

Note: The major version of this plugin follows the major version of Capacitor. Use the version that matches your Capacitor installation (e.g., plugin v8 for Capacitor 8). Only the latest major version is actively maintained.

Install

You can use our AI-Assisted Setup to install the plugin. Add the Capgo skills to your AI tool using the following command:

npx skills add https://github.com/cap-go/capacitor-skills --skill capacitor-plugins

Then use the following prompt:

Use the `capacitor-plugins` skill from `cap-go/capacitor-skills` to install the `@capgo/capacitor-health` plugin in my project.

If you prefer Manual Setup, install the plugin by running the following commands and follow the platform-specific instructions below:

npm install @capgo/capacitor-health
npx cap sync

iOS Setup

  1. Open your Capacitor application's Xcode workspace and enable the HealthKit capability.
  2. Provide usage descriptions in Info.plist (update the copy for your product):
<key>NSHealthShareUsageDescription</key>
<string>This app reads your health data to personalise your experience.</string>
<key>NSHealthUpdateUsageDescription</key>
<string>This app writes new health entries that you explicitly create.</string>

Android Setup

This plugin now uses Health Connect instead of Google Fit. Make sure your app meets the requirements below:

  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.
  2. Declare Health permissions. The plugin manifest ships with the required <uses-permission> declarations for basic data types (READ_/WRITE_STEPS, READ_/WRITE_DISTANCE, READ_/WRITE_ACTIVE_CALORIES_BURNED, READ_/WRITE_HEART_RATE, READ_/WRITE_WEIGHT, READ_/WRITE_SLEEP, READ_/WRITE_RESPIRATORY_RATE, READ_/WRITE_OXYGEN_SATURATION, READ_/WRITE_RESTING_HEART_RATE, READ_/WRITE_HEART_RATE_VARIABILITY). Your app does not need to duplicate them, but you must surface a user-facing rationale because the permissions are considered health sensitive.
  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.
  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).
  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 section below.

If you already used Google Fit in your project you can remove the associated dependencies (play-services-fitness, play-services-auth, OAuth configuration, etc.).

Privacy Policy Setup

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.

Option 1: HTML file in assets (recommended for simple cases)

Place an HTML file at android/app/src/main/assets/public/privacypolicy.html:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>Privacy Policy</title>
  </head>
  <body>
    <h1>Privacy Policy</h1>
    <p>Your privacy policy content here...</p>
    <h2>Health Data</h2>
    <p>Explain how you collect, use, and protect health data...</p>
  </body>
</html>

Option 2: Custom URL (recommended for hosted privacy policies)

Add a string resource to your app's android/app/src/main/res/values/strings.xml:

<resources>
    <!-- Your other strings... -->
    <string name="health_connect_privacy_policy_url">https://yourapp.com/privacy-policy</string>
</resources>

This URL will be loaded in a WebView when the user requests to see your privacy policy.

Programmatic access:

You can also show the privacy policy or open Health Connect settings from your app:

// Show the privacy policy screen
await Health.showPrivacyPolicy();

// Open Health Connect settings (useful for managing permissions)
await Health.openHealthConnectSettings();

Usage

import { Health } from '@capgo/capacitor-health';

// Verify that the native health SDK is present on this device
const availability = await Health.isAvailable();
if (!availability.available) {
  console.warn('Health access unavailable:', availability.reason);
}

// Ask for separate read/write access scopes
await Health.requestAuthorization({
  read: ['steps', 'heartRate', 'weight'],
  write: ['weight'],
});

// Query the last 50 step samples from the past 24 hours
const { samples } = await Health.readSamples({
  dataType: 'steps',
  startDate: new Date(Date.now() - 24 * 60 * 60 * 1000).toISOString(),
  endDate: new Date().toISOString(),
  limit: 50,
});

// Persist a new body-weight entry (kilograms by default)
await Health.saveSample({
  dataType: 'weight',
  value: 74.3,
});

Supported data types

IdentifierDefault unitNotes
stepscountStep count deltas
distancemeterWalking / running distance
calorieskilocalorieActive energy burned
heartRatebpmBeats per minute
weightkilogramBody mass
sleepminuteSleep sessions with duration and states
respiratoryRatebpmBreaths per minute
oxygenSaturationpercentBlood oxygen saturation (SpO2)
restingHeartRatebpmResting heart rate
heartRateVariabilitymillisecondHeart rate variability (HRV)
vo2MaxmL/min/kgVO2 max
bloodPressuremmHgBlood pressure (requires systolic/diastolic values)
bloodGlucosemg/dLBlood glucose level
bodyTemperaturecelsiusBody temperature
heightcentimeterBody height
flightsClimbedcountFloors / flights of stairs climbed
exerciseTimeminuteApple Exercise Time (iOS only)
distanceCyclingmeterCycling distance
bodyFatpercentBody fat percentage
basalBodyTemperaturecelsiusBasal body temperature
basalCalorieskilocalorieBasal metabolic rate / resting energy
totalCalorieskilocalorieTotal energy burned (active + basal)
mindfulnessminuteMindfulness / meditation sessions
appleStandHourcountApple Watch stand hours (iOS only, read-only; 1 = stood)
dietaryWaterliterWater consumed
dietaryEnergyConsumedkilocalorieDietary energy (calories) consumed
stateOfMindvalenceState of Mind (iOS 18+, read-only; value = valence -1...1)
workoutsN/AWorkout sessions (read-only, use with queryWorkouts())

All write operations expect the default unit shown above. On Android the metadata option is currently ignored by Health Connect.

Blood Pressure: Blood pressure requires both systolic and diastolic values:

await Health.saveSample({
  dataType: 'bloodPressure',
  value: 120, // systolic value (used as main value)
  systolic: 120,
  diastolic: 80,
  startDate: new Date().toISOString(),
});

// Reading blood pressure returns samples with systolic/diastolic fields
const { samples } = await Health.readSamples({
  dataType: 'bloodPressure',
  startDate: new Date(Date.now() - 24 * 60 * 60 * 1000).toISOString(),
  endDate: new Date().toISOString(),
});

samples.forEach((sample) => {
  console.log(`BP: ${sample.systolic}/${sample.diastolic} mmHg`);
});

Note about workouts: To query workout data using queryWorkouts(), you need to explicitly request workouts permission:

await Health.requestAuthorization({
  read: ['steps', 'workouts'], // Include 'workouts' to access workout sessions
});

Reading data older than 30 days (Android)

On Android, Health Connect caps reads to roughly the last 30 days unless your app holds the android.permission.health.READ_HEALTH_DATA_HISTORY permission. To read older history, set requestHistoryAccess: true on your normal requestAuthorization() call. The permission then appears in the first-time Health Connect permission sheet alongside your data-type permissions, instead of forcing users to grant it manually in Health Connect settings.

const status = await Health.requestAuthorization({
  read: ['steps', 'heartRate'],
  write: [],
  requestHistoryAccess: true,
});

// On Android, whether the history permission was granted:
console.log(status.historyAccessAuthorized); // true | false
// And whether the provider supports it at all:
console.log(status.historyAccessAvailable); // true | false

The result is reported back as the top-level historyAccessAuthorized boolean (present only when requestHistoryAccess was set). The same option works with checkAuthorization().

The READ_HEALTH_DATA_HISTORY permission only exists on sufficiently new Health Connect providers (Android 14 extension 13+ or Health Connect APK 171302+). On an older but otherwise supported provider the permission can never be granted, so the plugin checks feature availability and silently skips the history permission when it is unavailable, your normal read/write scopes are still requested as usual. In that case the status reports historyAccessAvailable: false (and historyAccessAuthorized: false), which lets you distinguish "the device can't do this" from "the user denied it" and avoid re-prompting. historyAccessAvailable is omitted unless requestHistoryAccess was set, and always omitted on iOS.

You must also declare the permission in your app's AndroidManifest.xml:

<uses-permission android:name="android.permission.health.READ_HEALTH_DATA_HISTORY" />

Health Connect only shows permissions that are both declared in the manifest and passed to the permission request, so this declaration is required for requestHistoryAccess to take effect. On iOS, HealthKit has no equivalent permission and no 30-day read cap, so requestHistoryAccess is ignored and historyAccessAuthorized is omitted from the returned status.

See Google's documentation on reading historical Health Connect data for more details.

Pagination example: Use the anchor parameter to paginate through workout results:

// First page: get the first 10 workouts
let result = await Health.queryWorkouts({
  startDate: new Date(Date.now() - 30 * 24 * 60 * 60 * 1000).toISOString(), // Last 30 days
  endDate: new Date().toISOString(),
  limit: 10,
});

console.log(`Found ${result.workouts.length} workouts`);

// If there are more results, the anchor will be set
while (result.anchor) {
  // Next page: use the anchor to continue from where we left off
  result = await Health.queryWorkouts({
    startDate: new Date(Date.now() - 30 * 24 * 60 * 60 * 1000).toISOString(),
    endDate: new Date().toISOString(),
    limit: 10,
    anchor: result.anchor, // Continue from the last result
  });

  console.log(`Found ${result.workouts.length} more workouts`);
}

New Data Types Examples

Sleep data:

// Request permission for sleep data
await Health.requestAuthorization({
  read: ['sleep'],
});

// Read sleep sessions from the past week
const { samples } = await Health.readSamples({
  dataType: 'sleep',
  startDate: new Date(Date.now() - 7 * 24 * 60 * 60 * 1000).toISOString(),
  endDate: new Date().toISOString(),
});

samples.forEach(sample => {
  console.log(`Sleep: ${sample.value} minutes, state: ${sample.sleepState}`);
});

Respiratory rate, oxygen saturation, and HRV:

// Request permission
await Health.requestAuthorization({
  read: ['respiratoryRate', 'oxygenSaturation', 'restingHeartRate', 'heartRateVariability'],
});

// Read respiratory rate
const { samples: respiratoryRate } = await Health.readSamples({
  dataType: 'respiratoryRate',
  startDate: new Date(Date.now() - 24 * 60 * 60 * 1000).toISOString(),
  endDate: new Date().toISOString(),
});

// Read oxygen saturation (SpO2)
const { samples: oxygenSat } = await Health.readSamples({
  dataType: 'oxygenSaturation',
  startDate: new Date(Date.now() - 24 * 60 * 60 * 1000).toISOString(),
  endDate: new Date().toISOString(),
});

Aggregated Queries

For large date ranges, use queryAggregated() to get aggregated data efficiently instead of fetching individual samples:

// Get daily step totals for the past month
const { samples } = await Health.queryAggregated({
  dataType: 'steps',
  startDate: new Date(Date.now() - 30 * 24 * 60 * 60 * 1000).toISOString(),
  endDate: new Date().toISOString(),
  bucket: 'day',        // Options: 'hour', 'day', 'week', 'month'
  aggregation: 'sum',   // Options: 'sum', 'average', 'min', 'max'
});

samples.forEach(sample => {
  console.log(`${sample.startDate}: ${sample.value} ${sample.unit}`);
});

// Request several aggregations at once by passing an array. Each result is returned
// in `sample.values`, keyed by aggregation name (`sample.value` holds the first one).
const { samples: hr } = await Health.queryAggregated({
  dataType: 'heartRate',
  startDate: new Date(Date.now() - 7 * 24 * 60 * 60 * 1000).toISOString(),
  endDate: new Date().toISOString(),
  bucket: 'day',
  aggregation: ['average', 'min', 'max'],
});

hr.forEach(sample => {
  console.log(`${sample.startDate}: avg=${sample.values.average}, min=${sample.values.min}, max=${sample.values.max}`);
});

Note: Aggregated queries are not supported for sleep, respiratory rate, oxygen saturation, heart rate variability, and VO2 max data types. These measurements should use readSamples(), not queryAggregated(). Aggregation is supported for: steps, distance, calories, dietary water, dietary energy consumed, heart rate, weight, and resting heart rate.

API

isAvailable()

isAvailable() => Promise<AvailabilityResult>

Returns whether the current platform supports the native health SDK.

Returns: Promise<AvailabilityResult>


requestAuthorization(...)

requestAuthorization(options: AuthorizationOptions) => Promise<AuthorizationStatus>

Requests read/write access to the provided data types.

Set requestHistoryAccess: true to additionally request Android's READ_HEALTH_DATA_HISTORY permission in the same Health Connect permission sheet (see {@link AuthorizationOptions.requestHistoryAccess}). The granted/denied status is reported back as historyAccessAuthorized on the result.

ParamType
optionsAuthorizationOptions

Returns: Promise<AuthorizationStatus>


checkAuthorization(...)

checkAuthorization(options: AuthorizationOptions) => Promise<AuthorizationStatus>

Checks authorization status for the provided data types without prompting the user.

ParamType
optionsAuthorizationOptions

Returns: Promise<AuthorizationStatus>


readSamples(...)

readSamples(options: QueryOptions) => Promise<ReadSamplesResult>

Reads samples for the given data type within the specified time frame.

ParamType
optionsQueryOptions

Returns: Promise<ReadSamplesResult>


saveSample(...)

saveSample(options: WriteSampleOptions) => Promise<void>

Writes a single sample to the native health store.

ParamType
optionsWriteSampleOptions

getPluginVersion()

getPluginVersion() => Promise<{ version: string; }>

Get the native Capacitor plugin version

Returns: Promise<{ version: string; }>


openHealthConnectSettings()

openHealthConnectSettings() => Promise<void>

Opens the Health Connect settings screen (Android only). On iOS, this method does nothing.

Use this to direct users to manage their Health Connect permissions or to install Health Connect if not available.


showPrivacyPolicy()

showPrivacyPolicy() => Promise<void>

Shows the app's privacy policy for Health Connect (Android only). On iOS, this method does nothing.

This displays the same privacy policy screen that Health Connect shows when the user taps "Privacy policy" in the permissions dialog.

The privacy policy URL can be configured by adding a string resource named "health_connect_privacy_policy_url" in your app's strings.xml, or by placing an HTML file at www/privacypolicy.html in your assets.


queryWorkouts(...)

queryWorkouts(options: QueryWorkoutsOptions) => Promise<QueryWorkoutsResult>

Queries workout sessions from the native health store. Supported on iOS (HealthKit) and Android (Health Connect).

ParamTypeDescription
optionsQueryWorkoutsOptionsQuery options including optional workout type filter, date range, limit, and sort order

Returns: Promise<QueryWorkoutsResult>


queryAggregated(...)

queryAggregated(options: QueryAggregatedOptions) => Promise<QueryAggregatedResult>

Queries aggregated health data from the native health store. Aggregates data into time buckets (hour, day, week, month) with operations like sum, average, min, or max. This is more efficient than fetching individual samples for large date ranges.

Supported on iOS (HealthKit) and Android (Health Connect).

ParamTypeDescription
optionsQueryAggregatedOptionsQuery options including data type, date range, bucket size, and aggregation type

Returns: Promise<QueryAggregatedResult>


Interfaces

AvailabilityResult

PropTypeDescription
availableboolean
platform'ios' | 'android' | 'web'Platform specific details (for debugging/diagnostics).
reasonstring

AuthorizationStatus

PropTypeDescription
readAuthorizedHealthDataType[]
readDeniedHealthDataType[]
writeAuthorizedHealthDataType[]
writeDeniedHealthDataType[]
historyAccessAuthorizedbooleanAndroid only: whether the READ_HEALTH_DATA_HISTORY permission is granted. Only present when requestHistoryAccess was set on the request; omitted otherwise and always omitted on iOS. Always false when historyAccessAvailable is false, since an unsupported provider can never grant the permission.
historyAccessAvailablebooleanAndroid only: whether the connected Health Connect provider supports the READ_HEALTH_DATA_HISTORY permission at all. Only present when requestHistoryAccess was set on the request; omitted otherwise and always omitted on iOS. false means the provider is too old (pre Android 14 extension 13 / Health Connect APK 171302) to ever grant history access — distinct from the user simply denying it. Use it to avoid re-prompting and to message the user that history access is unavailable on their device.

AuthorizationOptions

PropTypeDescription
readHealthDataType[]Data types that should be readable after authorization.
writeHealthDataType[]Data types that should be writable after authorization.
requestHistoryAccessbooleanAndroid only: also request the READ_HEALTH_DATA_HISTORY permission in the same Health Connect permission sheet. Without it, Health Connect caps reads to roughly the last 30 days; granting it lets you read older data. The consuming app must also declare the permission in its AndroidManifest.xml: &lt;uses-permission android:name="android.permission.health.READ_HEALTH_DATA_HISTORY" /&gt; The permission only exists on sufficiently new Health Connect providers (Android 14 extension 13+ or Health Connect APK 171302+). On older but otherwise supported providers it is silently skipped — the normal read/write scopes are still requested — and the returned status reports historyAccessAvailable: false. Ignored on iOS (HealthKit has no equivalent permission and no 30-day read cap).

ReadSamplesResult

PropType
samplesHealthSample[]

HealthSample

PropTypeDescription
dataTypeHealthDataType
valuenumber
unitHealthUnit
startDatestring
endDatestring
sourceNamestring
sourceIdstring
deviceTypestringAndroid only. The recording device's type, when Health Connect reports one: 'watch' | 'phone' | 'scale' | 'ring' | 'headMounted' | 'fitnessBand' | 'chestStrap' | 'smartDisplay'. Useful when a record carries a device type but no manufacturer/model, where sourceName falls back to the package name and cannot distinguish a watch from a phone.
platformIdstringPlatform-specific unique identifier (HealthKit UUID on iOS, Health Connect metadata ID on Android).
sleepStateSleepStateFor sleep data, indicates the sleep state (e.g., 'asleep', 'awake', 'rem', 'deep', 'light').
standState'stood' | 'idle'For Apple Stand Hour data (iOS only), whether the hour counted as stood or idle. value is normalized to 1 for stood and 0 for idle, so summing values per day yields the Activity ring's stand-hour count.
stateOfMindKind'momentaryEmotion' | 'dailyMood'For State of Mind data (iOS 18+), whether the sample is a momentary emotion or the day's overall mood. value carries the valence in [-1, 1] (unpleasant to pleasant). Omitted for kinds introduced after this plugin version.
stagesSleepStage[]For sleep data, individual sleep stages when the platform exposes stage-level data.
hasStageDatabooleanFor sleep data, indicates whether stage-level data was emitted.
systolicnumberFor blood pressure data, the systolic value in mmHg.
diastolicnumberFor blood pressure data, the diastolic value in mmHg.
measurementMethodnumberFor VO2 max data on Android, Health Connect's measurement method enum value.

SleepStage

Stage-level sleep segment emitted for sleep samples when platform data is available.

PropTypeDescription
startDatestringStage segment start date in ISO 8601 format.
endDatestringStage segment end date in ISO 8601 format.
stageSleepStateSleep stage label for this segment.
durationMinutesnumberDuration of this stage segment in minutes.

QueryOptions

PropTypeDescription
dataTypeHealthDataTypeThe type of data to retrieve from the health store.
startDatestringInclusive ISO 8601 start date (defaults to now - 1 day).
endDatestringExclusive ISO 8601 end date (defaults to now).
limitnumberMaximum number of samples to return (defaults to 100).
ascendingbooleanReturn results sorted ascending by start date (defaults to false).

WriteSampleOptions

PropTypeDescription
dataTypeHealthDataType
valuenumber
unitHealthUnitOptional unit override. If omitted, the default unit for the data type is used (count for steps, meter for distance, kilocalorie for calories, bpm for heartRate, kilogram for weight).
startDatestringISO 8601 start date for the sample. Defaults to now.
endDatestringISO 8601 end date for the sample. Defaults to startDate.
metadataRecord<string, string>Metadata key-value pairs forwarded to the native APIs where supported.
mindfulnessSessionType'meditation' | 'unknown' | 'breathing' | 'music' | 'movement' | 'unguided'Android mindfulness session type. Defaults to 'meditation' when dataType is 'mindfulness'.
systolicnumberFor blood pressure data, the systolic value in mmHg. Required when dataType is 'bloodPressure'.
diastolicnumberFor blood pressure data, the diastolic value in mmHg. Required when dataType is 'bloodPressure'.

QueryWorkoutsResult

PropTypeDescription
workoutsWorkout[]
anchorstringAnchor for the next page of results. Pass this value as the anchor parameter in the next query to continue pagination. If undefined or null, there are no more results.

Workout

PropTypeDescription
workoutTypeWorkoutTypeThe type of workout.
durationnumberDuration of the workout in seconds.
totalEnergyBurnednumberTotal energy burned in kilocalories (if available).
totalDistancenumberTotal distance in meters (if available).
startDatestringISO 8601 start date of the workout.
endDatestringISO 8601 end date of the workout.
sourceNamestringSource name that recorded the workout.
sourceIdstringSource bundle identifier.
platformIdstringPlatform-specific unique identifier (HealthKit UUID on iOS, Health Connect metadata ID on Android).
metadataRecord<string, string>Additional metadata (if available).
workoutEventsWorkoutEvent[]Lap workout events when available. On iOS, includes HealthKit lap markers with per-lap duration and optional distance.

WorkoutEvent

PropTypeDescription
typestringWorkout event type. iOS returns lap events from HealthKit (HKWorkoutEventType.lap).
datestringISO 8601 timestamp of the event.
durationSecondsnumberDuration of the lap interval in seconds until the next lap event or the workout end. Present for lap events returned on iOS.
distanceMetersnumberLap distance in meters when HealthKit provides it on the workout event metadata (for example HKMetadataKeyLapLength).

QueryWorkoutsOptions

PropTypeDescription
workoutTypeWorkoutTypeOptional workout type filter. If omitted, all workout types are returned.
startDatestringInclusive ISO 8601 start date (defaults to now - 1 day).
endDatestringExclusive ISO 8601 end date (defaults to now).
limitnumberMaximum number of workouts to return (defaults to 100).
ascendingbooleanReturn results sorted ascending by start date (defaults to false).
anchorstringAnchor for pagination. Use the anchor returned from a previous query to continue from that point. On iOS, this is the ISO 8601 cursor returned by the previous query. On Android, this uses Health Connect's pageToken. Omit this parameter to start from the beginning.

QueryAggregatedResult

PropType
samplesAggregatedSample[]

AggregatedSample

PropTypeDescription
startDatestringISO 8601 start date of the bucket.
endDatestringISO 8601 end date of the bucket.
valuenumberAggregated value for the bucket. When multiple aggregations are requested, this holds the value of the first requested aggregation that produced a result. See {@link values} for every requested aggregation.
valuesPartial<Record<AggregationType, number>>Map of each requested aggregation type to its aggregated value for the bucket.
unitHealthUnitUnit of the aggregated value.

QueryAggregatedOptions

PropTypeDescription
dataTypeHealthDataTypeThe type of data to aggregate from the health store.
startDatestringInclusive ISO 8601 start date (defaults to now - 1 day).
endDatestringExclusive ISO 8601 end date (defaults to now).
bucketBucketTypeTime bucket for aggregation (defaults to 'day').
aggregationAggregationType | AggregationType[]Aggregation operation(s) to perform (defaults to 'sum'). Pass a single {@link AggregationType} to compute one aggregation, or an array to compute several in a single query. Each requested aggregation is returned in {@link AggregatedSample.values}, keyed by its name.

Type Aliases

HealthDataType

'steps' | 'distance' | 'calories' | 'heartRate' | 'weight' | 'sleep' | 'respiratoryRate' | 'oxygenSaturation' | 'restingHeartRate' | 'heartRateVariability' | 'vo2Max' | 'bloodPressure' | 'bloodGlucose' | 'bodyTemperature' | 'height' | 'flightsClimbed' | 'exerciseTime' | 'distanceCycling' | 'bodyFat' | 'basalBodyTemperature' | 'appleSleepingWristTemperature' | 'basalCalories' | 'totalCalories' | 'mindfulness' | 'appleStandHour' | 'dietaryWater' | 'dietaryEnergyConsumed' | 'stateOfMind' | 'workouts'

HealthUnit

'count' | 'meter' | 'kilocalorie' | 'bpm' | 'kilogram' | 'minute' | 'percent' | 'millisecond' | 'mL/min/kg' | 'mmHg' | 'mg/dL' | 'celsius' | 'fahrenheit' | 'centimeter' | 'liter' | 'valence'

SleepState

'inBed' | 'asleep' | 'awake' | 'rem' | 'deep' | 'light'

Record

Construct a type with a set of properties K of type T

{ [P in K]: T; }

WorkoutType

'americanFootball' | 'australianFootball' | 'badminton' | 'baseball' | 'basketball' | 'bowling' | 'boxing' | 'climbing' | 'cricket' | 'crossTraining' | 'curling' | 'cycling' | 'dance' | 'elliptical' | 'fencing' | 'functionalStrengthTraining' | 'golf' | 'gymnastics' | 'handball' | 'hiking' | 'hockey' | 'jumpRope' | 'kickboxing' | 'lacrosse' | 'martialArts' | 'pilates' | 'racquetball' | 'rowing' | 'rugby' | 'running' | 'sailing' | 'skatingSports' | 'skiing' | 'snowboarding' | 'soccer' | 'softball' | 'squash' | 'stairClimbing' | 'strengthTraining' | 'surfing' | 'swimming' | 'swimmingPool' | 'swimmingOpenWater' | 'tableTennis' | 'tennis' | 'trackAndField' | 'traditionalStrengthTraining' | 'volleyball' | 'walking' | 'waterFitness' | 'waterPolo' | 'waterSports' | 'weightlifting' | 'wheelchair' | 'yoga' | 'archery' | 'barre' | 'cooldown' | 'coreTraining' | 'crossCountrySkiing' | 'discSports' | 'downhillSkiing' | 'equestrianSports' | 'fishing' | 'fitnessGaming' | 'flexibility' | 'handCycling' | 'highIntensityIntervalTraining' | 'hunting' | 'mindAndBody' | 'mixedCardio' | 'paddleSports' | 'pickleball' | 'play' | 'preparationAndRecovery' | 'snowSports' | 'stairs' | 'stepTraining' | 'surfingSports' | 'taiChi' | 'transition' | 'underwaterDiving' | 'wheelchairRunPace' | 'wheelchairWalkPace' | 'wrestling' | 'cardioDance' | 'socialDance' | 'backExtension' | 'barbellShoulderPress' | 'benchPress' | 'benchSitUp' | 'bikingStationary' | 'bootCamp' | 'burpee' | 'calisthenics' | 'crunch' | 'dancing' | 'deadlift' | 'dumbbellCurlLeftArm' | 'dumbbellCurlRightArm' | 'dumbbellFrontRaise' | 'dumbbellLateralRaise' | 'dumbbellTricepsExtensionLeftArm' | 'dumbbellTricepsExtensionRightArm' | 'dumbbellTricepsExtensionTwoArm' | 'exerciseClass' | 'forwardTwist' | 'frisbeedisc' | 'guidedBreathing' | 'iceHockey' | 'iceSkating' | 'jumpingJack' | 'latPullDown' | 'lunge' | 'meditation' | 'paddling' | 'paraGliding' | 'plank' | 'rockClimbing' | 'rollerHockey' | 'rowingMachine' | 'runningTreadmill' | 'scubaDiving' | 'skating' | 'snowshoeing' | 'stairClimbingMachine' | 'st

版本与发布记录

@capgo/capacitor-health 共发布 111 个版本,首次发布于 2025/09/24;过去 12 个月发布了 88 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
8.12.1latest2026/11/09今天
8.12.02026/11/072 天前
8.11.142026/11/026 天前
8.11.132026/10/2613 天前
8.11.122026/10/1525 天前
8.11.112026/10/1327 天前

关于 @capgo/capacitor-health 的常见问题

@capgo/capacitor-health 是什么?

Capacitor plugin to interact with data from Apple HealthKit and Health Connect

如何安装 @capgo/capacitor-health?

在项目目录运行 npm install @capgo/capacitor-health,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:@capacitor/core(>=8.0.0)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@capgo/capacitor-health 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@capgo/capacitor-health 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@capgo/capacitor-health 可以商用吗?

@capgo/capacitor-health 使用 MPL-2.0 许可。弱 Copyleft:可以商用,也可以和闭源代码一起使用;但如果分发时修改了 MPL 授权的文件,这些文件的修改需以 MPL 开源。以上为概括,不构成法律意见,请以许可原文为准。

@capgo/capacitor-health 的下载量有多少?

根据 npm 官方下载统计,@capgo/capacitor-health 在 2026/10/09 – 2026/11/07 这 30 天内被下载 205,396 次,日均约 6,847 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@capgo/capacitor-health 还在维护吗?

最新版本 8.12.1 发布于 2026/11/09(今天);至今共发布 111 个版本,其中过去 12 个月发布了 88 个;首次发布于 2025/09/24。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。