# @capgo/capacitor-health 中文文档

规范地址：https://npmcn.com/package/%40capgo/capacitor-health/

版本：8\.12\.1
npm 元数据更新时间：2026-11-09T07:21:00.055Z
中文译文更新时间：2026-11-09T02:09:11.196Z
软件包许可：MPL-2\.0

本文由上游 README 翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/%40capgo/capacitor-health
原文对照：https://npmcn.com/package/%40capgo/capacitor-health/?lang=original
项目主页：https://capgo.app/docs/plugins/health/
源码仓库：https://github.com/Cap-go/capacitor-health

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：372 kB，30 个文件
- 模块格式：ESM + CJS
- TypeScript 类型：包内自带
- 运行依赖：0 个
- peer 依赖：@capacitor/core \>=8\.0\.0
- 首次发布：2025-09-24T11:26:03.074Z
- 最新版本发布：2026-11-09T07:20:59.667Z
- 近 30 天下载量：205396（2026-10-09 至 2026-11-07，npm 官方下载统计）
- 已发布版本数：111（近 12 个月 88 个）

## 中文简介

与来自 Apple HealthKit 和 Health Connect 的数据交互的电容插件

## 安装

```sh
npm install @capgo/capacitor-health
```

也可以使用：`pnpm add @capgo/capacitor-health`、`yarn add @capgo/capacitor-health`、`bun add @capgo/capacitor-health`

## README

# @ capgo/ 电容器- 健康

与Apple HealthKit一起通过一个API在iOS和Health Connect上读取并写入健康数据. 建设健身,健康,医疗应用一次.

[![Capgo - Build Capacitor apps with AI, ship updates instantly](https://capgo.app/readme-banner.svg?repo=Cap-go/capacitor-health)](https://capgo.app/?ref=plugin_health)

**队长**:在几分钟内将修正推给您的 Capacitor 用户,在没有Mac的情况下构建已签名的iOS和Android apps,并在一击中回滚.

## [\*免费开始\*](https://capgo.app/register/?ref=plugin_health)

14天无限自由审判. 不需要信用卡

> 🤖 **建筑与AI编码代理?** 安装 [Capgo 技能](https://capgo.app/skills/?ref=plugin_health) 所以克劳德代码,代码,光标,副驾驶,或双子座CLI知道如何安装和使用 `@capgo/capacitor-health` 在您的电容应用程序中: `npx skills add Cap-go/capgo-skills`。然后问你的经纪人: _添加@capgo/capor-health 到我的 Capacitor app上,并把它连接起来_ [代理设置指南](https://capgo.app/agents/?ref=plugin_health) • 妇女 [主机磁共振](https://capgo.app/docs/ai/mcp/?ref=plugin_health)

![@capgo/capacitor-health for Capacitor apps](https://raw.githubusercontent.com/Cap-go/capacitor-health/main/assets/github-social-preview.png)

## 主要特点

-   **读取样本**数字 : `readSamples()` 在一定时间范围内的阶梯、心率、睡眠和其他类型.
-   **写入样本**数字 : `saveSample()` 存储单个样本.
-   **工作与总数**数字 : `queryWorkouts()` 财务报告和审定财务报表 `queryAggregated()` 供摘要使用.
-   **授权**数字 : `requestAuthorization()` 财务报告和审定财务报表 `checkAuthorization()` 每个数据类型.
-   **健康连接帮助者**数字 : `openHealthConnectSettings()` 财务报告和审定财务报表 `showPrivacyPolicy()` 安卓号.
-   **平台**: iOS和Android. 互联网档案馆的存檔,存档日期2013-12-21. 一些数据类型和单位在iOS和Android之间有所不同,参见下方所支持的数据类型表. 在网上不可用.

## 为什么是卫生主管?

唯一一个 **免费**, (中文(简体) ), **统一** 支持最新本地 API 的 Capacitor 健康数据插件 :

-   **健康连接(Android)** - 使用Google最新的健康平台(取代已贬值的Google Fit)
-   **卫生知识(iOS)** - 与苹果公司的健康框架充分融合
-   **统一 API** - 具有一致单元的平台的相同类型脚本接口
-   **多种衡量标准** - 步道、距离、卡路里、心率、体重
-   **读取和写入** - 查询历史数据并保存新的健康条目
-   **现代标准** - 支持Android 8.0+和iOS 14+
-   **现代软件包管理** - 支持Swift软件包管理器(SPM)和CocoaPods(SPM-为Capacitor 8准备)

适合健身应用,健康跟踪器,健康平台,医疗应用.

## 文档

这里有最完整的医生: [https://capgo.app/docs/plugins/保健/](https://capgo.app/docs/plugins/health/)

## 兼容性

| 插件版本 | 电容兼容性 | 维护 |
| --- | --- | --- |
| 联合国 | 联合国 | ✅ |
| 页:1 | 页:1 | 应要求 |
| 页:1 | 页:1 | ❌ |
| 页:1 | 页:1 | ❌ |

> **说明:** 此插件的主要版本沿用了Capacitor的主要版本. 使用匹配您的 Capacitor 安装的版本( 如 Capacitor 8 的插件 v8) 。 只有最新的主要版本得到积极维护.

## 安装

您可以使用我们的 AI 辅助设置安装插件 。 使用以下命令将 Capgo 技能添加到您的 AI 工具 :

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

然后使用下列提示:

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

如果您更喜欢手动设置,请通过运行以下命令来安装插件,并遵循下面的平台特定指令:

```bash
npm install @capgo/capacitor-health
npx cap sync
```

## iOS 设置

1.  打开您的 Capacitor 应用程序的 Xcode 工作空间并启用 **卫生科** 能力.
2.  提供使用描述 `Info.plist` (更新副本 对于您的产品):

```xml
<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 设置

此插件现在使用 [健康连接](https://developer.android.com/health-and-fitness/guides/health-connect) 而不是Google Fit。 (笑声) 确保您的应用程序符合以下要求:

1.  **Min SDK 26+ (英语).** 健康连接仅在Android 8.0(API 26)及以上版本提供. 插件的 Gradle 设置已经针对此关卡 .
2.  **申报健康许可.** 需要的外掛程式列表船 `<uses-permission>` 基本数据类型的声明`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`) (中文(简体) ). 您的应用程序不需要复制它们, 但是您必须显示一个用户化的原理, 因为权限被认为是健康敏感 .
3.  **确保安装健康连接.** Android 14+上的设备默认包括它. 对于较早的版本,用户必须安装 _由 Android 创建的健康连接_ 从游戏商店。 这个 `Health.isAvailable()` 帮助显示当前状态, 这样您就可以相应提示 .
4.  **请求运行时间访问.** 插件在您调用时打开健康连接权限UI `requestAuthorization`。您仍然应当处理拒绝流(例如,如果 `checkAuthorization` 报告缺少范围.
5.  **提供隐私政策.** 健康连接需要应用程序显示隐私政策,解释健康数据是如何使用的. 见 [隐私政策设置](https://npmcn.com/package/%40capgo/capacitor-health/#readme-privacy-policy-setup) 下节.

如果您已经在您的项目中使用了 Google Fit, 您可以删除相关的依赖性(`play-services-fitness`, (中文(简体) ), `play-services-auth`, OAuth 配置等).

### 隐私政策设置

健康连接需要您的应用程序提供隐私政策,以解释您如何处理健康数据. 当用户在健康连接权限对话框中点击"Privacy Policy"时,您的应用程序必须显示此信息.

**备选案文1:资产中的HTML文件(为简单案件推荐)**

将 HTML 文件放置在 `android/app/src/main/assets/public/privacypolicy.html`数字 :

```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>
```

**备选方案2:自定义 URL(为主机隐私政策推荐)**

在您的应用程序中添加字符串资源 `android/app/src/main/res/values/strings.xml`数字 :

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

当用户要求查看您的隐私政策时, 此 URL 将会被载入 WebView 中 .

**程序访问 :**

您也可以从您的应用程序中显示隐私政策或打开健康连接设置 :

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

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

## 使用量

```ts
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,
});
```

### 支持的数据类型

| 标识符 | 默认单位 | 页:1 |
| --- | --- | --- |
| `steps` | `count` | 步数三角洲 |
| `distance` | `meter` | 行走/ 运行距离 |
| `calories` | `kilocalorie` | 活性能被燃烧 |
| `heartRate` | `bpm` | 每分钟比分 |
| `weight` | `kilogram` | 体质 |
| `sleep` | `minute` | 有期限和状态的睡眠会 |
| `respiratoryRate` | `bpm` | 每分钟呼吸一次 |
| `oxygenSaturation` | `percent` | 血氧饱和(SpO2) |
| `restingHeartRate` | `bpm` | 中止心率 |
| `heartRateVariability` | `millisecond` | 心率可变性(HRV) |
| `vo2Max` | `mL/min/kg` | VO2 最大值 |
| `bloodPressure` | `mmHg` | 血压(需要血压/血压值) |
| `bloodGlucose` | `mg/dL` | 血糖水平 |
| `bodyTemperature` | `celsius` | 体温 |
| `height` | `centimeter` | 身高( 身高) |
| `flightsClimbed` | `count` | 楼层/上行楼梯 |
| `exerciseTime` | `minute` | 苹果练习时间( 仅iOS) |
| `distanceCycling` | `meter` | 循环距离 |
| `bodyFat` | `percent` | 体重百分比 |
| `basalBodyTemperature` | `celsius` | Basal体温 |
| `basalCalories` | `kilocalorie` | 活性代谢率/休息能量 |
| `totalCalories` | `kilocalorie` | 燃烧能源总量(活性+玄武岩) |
| `mindfulness` | `minute` | 思念/冥想会 |
| `appleStandHour` | `count` | 苹果卫视站点时间(仅iOS,只读;1=已站) |
| `dietaryWater` | `liter` | 用水量 |
| `dietaryEnergyConsumed` | `kilocalorie` | 消耗的饮食能(卡) |
| `stateOfMind` | `valence` | 心状态(iOS 18+,只读;值=valence-1..1) |
| `workouts` | 不详 | 解决会话(只读,使用 `queryWorkouts()`(中文(简体) ) |

所有写入操作都期望上面显示的默认单位. 安卓号上 `metadata` 选项目前被健康连接忽略.

**血压:** 血压要求同时有分泌和分泌值:

```ts
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`);
});
```

**关于锻炼的说明:** 使用 `queryWorkouts()`,需要明确请求 `workouts` 权限 :

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

### 读取超过30天的数据(Android)

在Android上,健康连接盖读取大致 **过去30天** 除非你的应用程序持有 `android.permission.health.READ_HEALTH_DATA_HISTORY` 允许。 阅读旧历史,设定 `requestHistoryAccess: true` 正常的时候 `requestAuthorization()` 电话 那么许可 与您的数据类型权限一起出现在首次健康连接授权页中, 而不是强迫用户在健康连接设置中手动授予.

```ts
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
```

结果报告为高层 `historyAccessAuthorized` 布尔( 仅在 `requestHistoryAccess` (已设定)。 同一选项与 `checkAuthorization()`。 。 。 .

这个 `READ_HEALTH_DATA_HISTORY` 仅允许足够新的健康连接供应商使用 (Android 14扩展13+或健康连接APK 171302+). 年长但得到支持的人 提供者永远不能被授予权限, 因此插件检查 [特性可用性](https://developer.android.com/health-and-fitness/health-connect/features/availability) 财务报告和审定财务报表 **悄悄跳过** 在无法使用历史记录时, 您的正常读取/ 写入范围 仍按惯例提出要求。 在这种情况下,情况报告 `historyAccessAvailable: false` (和 `historyAccessAuthorized: false`)),可以区分"设备不能做到这一点"和"设备不能做到这一点" 用户否认了",并避免了再发作. `historyAccessAvailable` 被省略,除非 `requestHistoryAccess` 在iOS上总是省略.

你必须 **(单位:千美元)** 在您的应用程序中声明许可 `AndroidManifest.xml`数字 :

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

健康连接只显示在清单中声明并传递给 许可请求,所以需要此声明 `requestHistoryAccess` 以生效。 打开 iOS,HealthKit没有相应的许可,也没有30天的读取上限,所以 `requestHistoryAccess` 实值 忽略和删除 `historyAccessAuthorized` 从返回状态中删除.

参见 Google 上的文档 [读取历史健康连接数据](https://developer.android.com/health-and-fitness/guides/health-connect/develop/read-data#read-restriction) 更多细节.

**缓冲示例 :** 使用 `anchor` 通过解决结果粘接的参数 :

```ts
// 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`);
}
```

### 新建数据类型示例

**睡眠数据 :**

```ts
// 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}`);
});
```

**呼吸速率、氧气饱和度和HRV:**

```ts
// 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(),
});
```

### 综合查询

大日期范围, 使用 `queryAggregated()` 以高效方式获取汇总数据,而不是获取单个样本:

```ts
// 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}`);
});
```

**说明:** 综合查询不支持睡眠,呼吸道速率,氧饱和,心率可变性,和VO2最大数据类型. 这些测量应使用 `readSamples()`没有 `queryAggregated()`支持综合:步道、距离、卡路里、饮食用水、所消耗的饮食能量、心率、体重和休息心率.

## API 密码

-   [`isAvailable()`](https://npmcn.com/package/%40capgo/capacitor-health/#readme-isavailable)
-   [`requestAuthorization(...)`](https://npmcn.com/package/%40capgo/capacitor-health/#readme-requestauthorization)
-   [`checkAuthorization(...)`](https://npmcn.com/package/%40capgo/capacitor-health/#readme-checkauthorization)
-   [`readSamples(...)`](https://npmcn.com/package/%40capgo/capacitor-health/#readme-readsamples)
-   [`saveSample(...)`](https://npmcn.com/package/%40capgo/capacitor-health/#readme-savesample)
-   [`getPluginVersion()`](https://npmcn.com/package/%40capgo/capacitor-health/#readme-getpluginversion)
-   [`openHealthConnectSettings()`](https://npmcn.com/package/%40capgo/capacitor-health/#readme-openhealthconnectsettings)
-   [`showPrivacyPolicy()`](https://npmcn.com/package/%40capgo/capacitor-health/#readme-showprivacypolicy)
-   [`queryWorkouts(...)`](https://npmcn.com/package/%40capgo/capacitor-health/#readme-queryworkouts)
-   [`queryAggregated(...)`](https://npmcn.com/package/%40capgo/capacitor-health/#readme-queryaggregated)
-   [接口](https://npmcn.com/package/%40capgo/capacitor-health/#readme-interfaces)
-   [类型异名](https://npmcn.com/package/%40capgo/capacitor-health/#readme-type-aliases)

### 易读 ()

```typescript
isAvailable() => Promise<AvailabilityResult>
```

返回当前平台是否支持本地健康 SDK .

**回返情况:** `Promise<[AvailabilityResult](https://npmcn.com/package/%40capgo/capacitor-health/#readme-availabilityresult)>`

* * *

### 请求认证(...)

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

请求读取/写入所提供的数据类型.

设定 `requestHistoryAccess: true` 除了另外请求Android的 `READ_HEALTH_DATA_HISTORY` 在同一健康连接许可单中的许可 (见qqlink [授权选项。 请求历史访问](https://npmcn.com/package/%40capgo/capacitor-health/#readme-authorizationoptions)) (中文(简体) ). 被授予/拒绝的地位是: 回报为 `historyAccessAuthorized` 在结果.

| 参数 | 类型 |
| --- | --- |
| **`options`** | `[AuthorizationOptions](https://npmcn.com/package/%40capgo/capacitor-health/#readme-authorizationoptions)` |

**回返情况:** `Promise<[AuthorizationStatus](https://npmcn.com/package/%40capgo/capacitor-health/#readme-authorizationstatus)>`

* * *

### 检查认证(...)

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

检查所提供数据类型的授权状态而不提示用户 .

| 参数 | 类型 |
| --- | --- |
| **`options`** | `[AuthorizationOptions](https://npmcn.com/package/%40capgo/capacitor-health/#readme-authorizationoptions)` |

**回返情况:** `Promise<[AuthorizationStatus](https://npmcn.com/package/%40capgo/capacitor-health/#readme-authorizationstatus)>`

* * *

### 读取样本(...)

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

在指定时限内读取给定数据类型的样本.

| 参数 | 类型 |
| --- | --- |
| **`options`** | `[QueryOptions](https://npmcn.com/package/%40capgo/capacitor-health/#readme-queryoptions)` |

**回返情况:** `Promise<[ReadSamplesResult](https://npmcn.com/package/%40capgo/capacitor-health/#readme-readsamplesresult)>`

* * *

### 保存样本(...)

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

将单一样本写入本土保健商店.

| 参数 | 类型 |
| --- | --- |
| **`options`** | `[WriteSampleOptions](https://npmcn.com/package/%40capgo/capacitor-health/#readme-writesampleoptions)` |

* * *

### 获取 PluginVersion ()

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

获取本地 Capacitor 插件版本

**回返情况:** `Promise<{ version: string; }>`

* * *

### 开放式健康连接设置( )

```typescript
openHealthConnectSettings() => Promise<void>
```

打开健康连接设置屏幕(只有Android). 在iOS上,这种方法没有任何作用.

用于引导用户管理其健康连接权限 或安装健康连接(如果没有的话).

* * *

### 显示隐私政策 ()

```typescript
showPrivacyPolicy() => Promise<void>
```

显示应用程序的"健康连接"(Android only)隐私政策. 在iOS上,这种方法没有任何作用.

此显示的隐私政策屏幕与健康连接显示的相同 当用户在权限对话框中点击"Privacy Policy"时.

隐私策略 URL 可以通过添加字符串资源来配置 在您的应用字符串. xml 中命名为“ 健康连接 privacy policy url”, 或将 HTML 文件放在www/privacypolicy。 html 在您的资产.

* * *

### 查询工作(...)

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

本地健康商店的查询会. 在iOS(健康Kit)和Android(健康连接)上得到支持.

| 参数 | 类型 | 说明 |
| --- | --- | --- |
| **`options`** | `[QueryWorkoutsOptions](https://npmcn.com/package/%40capgo/capacitor-health/#readme-queryworkoutsoptions)` | 查询选项,包括可选的解决类型过滤器、日期范围、限制和排序顺序 |

**回返情况:** `Promise<[QueryWorkoutsResult](https://npmcn.com/package/%40capgo/capacitor-health/#readme-queryworkoutsresult)>`

* * *

### 查询分类(...)

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

查询汇总了本地保健商店的健康数据. 将数据汇总为时间桶(小时、日、周、月),并进行总和、平均、分或最大等操作. 这比取取出大面积的单个样本更为有效.

在iOS(健康Kit)和Android(健康连接)上得到支持.

| 参数 | 类型 | 说明 |
| --- | --- | --- |
| **`options`** | `[QueryAggregatedOptions](https://npmcn.com/package/%40capgo/capacitor-health/#readme-queryaggregatedoptions)` | 查询选项,包括数据类型、日期范围、桶大小和汇总类型 |

**回返情况:** `Promise<[QueryAggregatedResult](https://npmcn.com/package/%40capgo/capacitor-health/#readme-queryaggregatedresult)>`

* * *

### 接口

#### 可用性

| Prop | 类型 | 说明 |
| --- | --- | --- |
| **`available`** | `boolean` |  |
| **`platform`** | `'ios' | 'android' | 'web'` | 平台具体细节(用于调试/诊断). |
| **`reason`** | `string` |  |

#### 授权现状

| Prop | 类型 | 说明 |
| --- | --- | --- |
| **`readAuthorized`** | `HealthDataType[]` |  |
| **`readDenied`** | `HealthDataType[]` |  |
| **`writeAuthorized`** | `HealthDataType[]` |  |
| **`writeDenied`** | `HealthDataType[]` |  |
| **`historyAccessAuthorized`** | `boolean` | 仅限机器人: `READ_HEALTH_DATA_HISTORY` 获得许可。 只在 `requestHistoryAccess` ; 省略了其他内容,并且总是省略了iOS。 永远 `false` 何时 `historyAccessAvailable` 实值 `false`,因为没有支持的提供者永远不能给予许可. |
| **`historyAccessAvailable`** | `boolean` | 仅限Android:连接的"健康连接"提供商是否支持 `READ_HEALTH_DATA_HISTORY` 完全允许。 只在 `requestHistoryAccess` ; 省略了其他内容,并且总是省略了iOS. `false` 指提供商已经太老了(Android 14扩展13 / Health Connect APK 171302),无法给予历史访问权——有别于用户仅仅否认. 使用它来避免再发热,并告诉用户其设备上没有历史访问. |

#### 授权选项

| Prop | 类型 | 说明 |
| --- | --- | --- |
| **`read`** | `HealthDataType[]` | 经批准后应可读取的数据类型. |
| **`write`** | `HealthDataType[]` | 经授权后应可写入文件的数据类型. |
| **`requestHistoryAccess`** | `boolean` | 仅限Android:也请求 `READ_HEALTH_DATA_HISTORY` 允许在同一健康连接许可单中。 没有它,"健康连接"(Health Connect)的封顶大约读取了过去30天;赋予它可以让你读取更旧的数据。 消费的应用软件还必须在其中宣布许可 `AndroidManifest.xml`数字 : `&lt;uses-permission android:name="android.permission.health.READ_HEALTH_DATA_HISTORY" /&gt;` 只有足够新的健康连接供应商(Android 14扩展13+或健康连接APK 171302+)才有这种许可. 关于较老但得到其他支持的提供者,它被默默地跳过——仍然要求正常的读取/写出范围——和返回的状况报告 `historyAccessAvailable: false`。忽略了iOS(HealthKit没有同等权限,也没有30天的阅读上限). |

#### 读取样本结果

| Prop | 类型 |
| --- | --- |
| **`samples`** | `HealthSample[]` |

#### 健康样板

| Prop | 类型 | 说明 |
| --- | --- | --- |
| **`dataType`** | `[HealthDataType](https://npmcn.com/package/%40capgo/capacitor-health/#readme-healthdatatype)` |  |
| **`value`** | `number` |  |
| **`unit`** | `[HealthUnit](https://npmcn.com/package/%40capgo/capacitor-health/#readme-healthunit)` |  |
| **`startDate`** | `string` |  |
| **`endDate`** | `string` |  |
| **`sourceName`** | `string` |  |
| **`sourceId`** | `string` |  |
| **`deviceType`** | `string` | 仅限Android. 录音设备的类型, 当健康连接报告 1 : “ watch ” QQ“ 手机 ” , “ scale ” , “ ring ” , “ head Mounted ” , “ fitness Band ” , “ chestStrap ” , “ smartDisplay ” 。 当记录载有设备类型但没有制造商/型号时有用 `sourceName` 倒回包名,无法区分表和手机. |
| **`platformId`** | `string` | 平台特有的独特标识符(HealthKit UUID on iOS,Health Connect medata ID on Android). |
| **`sleepState`** | `[SleepState](https://npmcn.com/package/%40capgo/capacitor-health/#readme-sleepstate)` | 对于睡眠数据,表示睡眠状态(如"睡眠","醒","rem","深","光"等). |
| **`standState`** | `'stood' | 'idle'` | 对于Apple Stand Hour数据(只有iOS数据)来说,无论小时算作已站或闲. `value` 正常化为站台1个,闲地0个,所以每天的蜂起值得出活动环的站点时数. |
| **`stateOfMindKind`** | `'momentaryEmotion' | 'dailyMood'` | 对于"心灵状态"数据(iOS 18+)来说,样本是暂时的情感还是当天的整体心情. `value` 载着在 \[1, 1\] 中的浮华。 此插件版本之后引入的种类 . |
| **`stages`** | `SleepStage[]` | 对于睡眠数据,当平台曝光相位数据时,单个睡眠阶段. |
| **`hasStageData`** | `boolean` | 关于睡眠数据,请说明是否排放了阶段数据. |
| **`systolic`** | `number` | 对于血压数据,以mmHg为单位的节律值. |
| **`diastolic`** | `number` | 对于血压数据,分泌值为mmHg. |
| **`measurementMethod`** | `number` | 对于Android上的VO2最大数据,Health Connect的测量方法enum值. |

#### 睡眠状态

平台数据可用时为睡眠样本排放的相位睡眠段.

| Prop | 类型 | 说明 |
| --- | --- | --- |
| **`startDate`** | `string` | 阶段段开始日期为ISO 8601格式. |
| **`endDate`** | `string` | 阶段段结束日期为ISO 8601格式. |
| **`stage`** | `[SleepState](https://npmcn.com/package/%40capgo/capacitor-health/#readme-sleepstate)` | 此段的睡眠舞台标签 . |
| **`durationMinutes`** | `number` | 这一阶段段的会期为几分钟. |

#### 查询选项

| Prop | 类型 | 说明 |
| --- | --- | --- |
| **`dataType`** | `[HealthDataType](https://npmcn.com/package/%40capgo/capacitor-health/#readme-healthdatatype)` | 从保健商店取回的数据类型. |
| **`startDate`** | `string` | 包含 ISO 8601 开始日期(默认为现在 - 1天). |
| **`endDate`** | `string` | 唯一 ISO 8601 结束日期( 默认为现在) . |
| **`limit`** | `number` | 要返回的最大样本数( 默认为 100) . |
| **`ascending`** | `boolean` | 返回结果按起始日期( 默认为假) 排序升起 . |

#### 写入示例选项

| Prop | 类型 | 说明 |
| --- | --- | --- |
| **`dataType`** | `[HealthDataType](https://npmcn.com/package/%40capgo/capacitor-health/#readme-healthdatatype)` |  |
| **`value`** | `number` |  |
| **`unit`** | `[HealthUnit](https://npmcn.com/package/%40capgo/capacitor-health/#readme-healthunit)` | 可选单元覆盖。 如果省略,则使用数据类型的默认单位(计算 `steps`计数器 `distance`,千卡路里为 `calories`页:1 `heartRate`单位:公斤 `weight`) (中文(简体) ). |
| **`startDate`** | `string` | ISO 8601 样本起始日期. 默认现在. |
| **`endDate`** | `string` | ISO 8601 样本结束日期. 默认启动 Date . |
| **`metadata`** | `[Record](https://npmcn.com/package/%40capgo/capacitor-health/#readme-record)<string, string>` | 元数据密钥值对已支持的本地API . |
| **`mindfulnessSessionType`** | `'meditation' | 'unknown' | 'breathing' | 'music' | 'movement' | 'unguided'` | Android 注意会话类型 。 当 DataType 是“ 注意” 时默认为“ 意图 ” . |
| **`systolic`** | `number` | 对于血压数据,以mmHg为单位的节律值. 数据类型为“ 血压 ” 时需要 . |
| **`diastolic`** | `number` | 对于血压数据,分泌值为mmHg. 数据类型为“ 血压 ” 时需要 . |

#### 查询工作结果

| Prop | 类型 | 说明 |
| --- | --- | --- |
| **`workouts`** | `Workout[]` |  |
| **`anchor`** | `string` | 下页结果锁定 。 在下一个查询中将此值作为锁定参数传递给继续 pagination 。 如果未定义或无效,则没有更多的结果. |

#### 工作

| Prop | 类型 | 说明 |
| --- | --- | --- |
| **`workoutType`** | `[WorkoutType](https://npmcn.com/package/%40capgo/capacitor-health/#readme-workouttype)` | 修行之类. |
| **`duration`** | `number` | 锻炼时间数秒. |
| **`totalEnergyBurned`** | `number` | 以千卡为单位燃烧的总能量(如果有的话). |
| **`totalDistance`** | `number` | 总距离以米计(如果有的话). |
| **`startDate`** | `string` | ISO 8601 工作开始日期. |
| **`endDate`** | `string` | ISO 8601 最终解决日期. |
| **`sourceName`** | `string` | 记录锻炼的源名. |
| **`sourceId`** | `string` | 源包标识符 . |
| **`platformId`** | `string` | 平台特有的独特标识符(HealthKit UUID on iOS,Health Connect medata ID on Android). |
| **`metadata`** | `[Record](https://npmcn.com/package/%40capgo/capacitor-health/#readme-record)<string, string>` | 补充元数据(如果有的话). |
| **`workoutEvents`** | `WorkoutEvent[]` | 空闲时拉普健身活动. 在iOS上,包括有平时长度和可选距离的HealthKit相圈标记. |

#### 解决事件

| Prop | 类型 | 说明 |
| --- | --- | --- |
| **`type`** | `string` | [工作](https://npmcn.com/package/%40capgo/capacitor-health/#readme-workout) 事件类型。 iOS 从 HealthKit 返回相圈事件(`HKWorkoutEventType.lap`) (中文(简体) ). |
| **`date`** | `string` | ISO 8601 事件时间戳. |
| **`durationSeconds`** | `number` | 以秒计的圈间距持续时间,直到下个圈事件或健身结束. iOS上回了圈内活动. |
| **`distanceMeters`** | `number` | 当HealthKit在解决事件元数据上提供时(例如 `HKMetadataKeyLapLength`) (中文(简体) ). |

#### 查询工作选项

| Prop | 类型 | 说明 |
| --- | --- | --- |
| **`workoutType`** | `[WorkoutType](https://npmcn.com/package/%40capgo/capacitor-health/#readme-workouttype)` | 可选的锻炼类型过滤器. 如果省略, 则返回全部的解决类型 . |
| **`startDate`** | `string` | 包含 ISO 8601 开始日期(默认为现在 - 1天). |
| **`endDate`** | `string` | 唯一 ISO 8601 结束日期( 默认为现在) . |
| **`limit`** | `number` | 返回的最大工作次数( 默认为 100) . |
| **`ascending`** | `boolean` | 返回结果按起始日期( 默认为假) 排序升起 . |
| **`anchor`** | `string` | 起锚作活页. 使用上次查询返回的锚从该点继续 。 在iOS上,这是由上个查询返回的ISO 8601光标. 在Android上,这个使用Health Connect的页面Token. 关闭此参数从头开始 . |

#### 查询分类结果

| Prop | 类型 |
| --- | --- |
| **`samples`** | `AggregatedSample[]` |

#### 总计样本

| Prop | 类型 | 说明 |
| --- | --- | --- |
| **`startDate`** | `string` | ISO 8601 桶开始日期. |
| **`endDate`** | `string` | ISO 8601 桶的结束日期. |
| **`value`** | `number` | 桶的总值。 当要求多重汇总时,这保持了产生结果的第一个请求汇总的价值. 在每个请求的聚合中, 请参看 QQlink 值 . |
| **`values`** | `[Partial](https://npmcn.com/package/%40capgo/capacitor-health/#readme-partial)<[Record](https://npmcn.com/package/%40capgo/capacitor-health/#readme-record)<[AggregationType](https://npmcn.com/package/%40capgo/capacitor-health/#readme-aggregationtype), number>>` | 每个请求的聚合类型及其对桶的集合值的地图. |
| **`unit`** | `[HealthUnit](https://npmcn.com/package/%40capgo/capacitor-health/#readme-healthunit)` | 总价值的单位. |

#### 查询分离选项

| Prop | 类型 | 说明 |
| --- | --- | --- |
| **`dataType`** | `[HealthDataType](https://npmcn.com/package/%40capgo/capacitor-health/#readme-healthdatatype)` | 从保健商店汇总的数据类型. |
| **`startDate`** | `string` | 包含 ISO 8601 开始日期(默认为现在 - 1天). |
| **`endDate`** | `string` | 唯一 ISO 8601 结束日期( 默认为现在) . |
| **`bucket`** | `[BucketType](https://npmcn.com/package/%40capgo/capacitor-health/#readme-buckettype)` | 集合的时间桶( 默认为"day" ) . |
| **`aggregation`** | `[AggregationType](https://npmcn.com/package/%40capgo/capacitor-health/#readme-aggregationtype) | AggregationType[]` | 要执行的聚合操作( 默认为" sum" ) 。 传出单一的QQ链接 [聚合类型](https://npmcn.com/package/%40capgo/capacitor-health/#readme-aggregationtype)} 计算一个聚合, 或数组在单个查询中计算若干。 每一个请求的汇总在QQlink中返回 [总体数值](https://npmcn.com/package/%40capgo/capacitor-health/#readme-aggregatedsample)),被它的名字所键入. |

### 类型异名

#### 卫生数据类型

`'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'`

#### 卫生股

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

#### 睡眠状态

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

#### 记录

构造 T 类型 K 的一组属性类型

`{ [P in K]: T; }`

#### 工作类型

`'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 是什么？

与来自 Apple HealthKit 和 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 和提交记录判断。

