快速入门
复制一条配置 prompt,包含安装步骤和该插件的完整 Markdown 指南。
Set up this Capacitor plugin in the project.
Use the package manager already used by the project.
Install these package(s): `@capgo/capacitor-health`
Run the required Capacitor sync/update step after installation.
Read this markdown guide for the full setup steps: https://raw.githubusercontent.com/Cap-go/website/refs/heads/main/apps/docs/src/content/docs/docs/plugins/health/getting-started.mdx
Use that guide for platform-specific steps, native file edits, permissions, config changes, imports, and usage setup.
If that guide references other docs pages, read them too.
你可以使用我们的 AI 辅助设置来安装插件。使用以下命令将 Capgo skills 添加到你的 AI 工具中:
npx skills add https://github.com/Cap-go/capgo-skills --skill capacitor-plugins然后使用以下 prompt:
Use the `capacitor-plugins` skill from `Cap-go/capgo-skills` to install the `@capgo/capacitor-health` plugin in my project.如果你更倾向于手动设置,请运行以下命令安装插件,并参考下文针对各平台的具体说明:
bun add @capgo/capacitor-healthbunx cap sync导入
“导入”章节import { Health } from '@capgo/capacitor-health';快速入门
“快速开始”章节检查可用性,申请所需类型的读取权限,然后查询指定日期范围。
import { Health } from '@capgo/capacitor-health';
async function loadTodaysSteps() { const { available, reason } = await Health.isAvailable(); if (!available) { console.warn('Health data not available', reason); return; }
await Health.requestAuthorization({ read: ['steps', 'heartRate'], write: ['weight'], });
const today = await Health.readSamples({ dataType: 'steps', startDate: new Date(Date.now() - 24 * 60 * 60 * 1000).toISOString(), endDate: new Date().toISOString(), limit: 500, });
return today;}示例:查询 30 天前的 Android 历史数据
标题为“示例:查询 30 天前的 Android 历史数据”的部分除非用户授予权限,否则 Health Connect 会限制历史数据的读取 READ_HEALTH_DATA_HISTORY。请通过以下方式选择加入: requestHistoryAccess: true 并在你的 Android manifest 中声明该权限:
<uses-permission android:name="android.permission.health.READ_HEALTH_DATA_HISTORY" />await Health.requestAuthorization({ read: ['steps'], requestHistoryAccess: true,});检查 historyAccessAvailable 和 historyAccessAuthorized 根据结果决定是否显示设置页面的 deep link。
示例:记录体重样本
标题为“示例:记录体重样本”的章节await Health.saveSample({ dataType: 'weight', value: 72.4, unit: 'kilogram', startDate: new Date().toISOString(), endDate: new Date().toISOString(),});示例:带阶段的睡眠
标题为“示例:带阶段的睡眠”的章节请求 sleep 在 read,然后读取该夜间时间窗口内的样本。当平台提供阶段数据时,样本可以包含 SleepStage 分段(deep, rem, light,等)。
常见坑点
标题为“常见坑点”的章节- 授权按数据类型划分: 请预先请求
HealthDataType所有需要读写的数据。 - Android Health Connect 安装状态: use
isAvailable和openHealthConnectSettings当提供程序缺失或禁用时使用。 - 历史记录权限仅限 Android: iOS 会忽略此项,因为 iOS 没有 30 天限制。
- 在 prompt 前进行检查: 使用
checkAuthorization以在调用前渲染 UIrequestAuthorization再次尝试。
API 概览
“API 概览”章节isAvailable
标题为“isAvailable”的章节返回当前平台是否支持原生健康 SDK。
import { Health } from '@capgo/capacitor-health';
const result = await Health.isAvailable();console.log(result);requestAuthorization
标题为 “requestAuthorization” 的章节请求对所提供数据类型的读/写权限。
import { Health } from '@capgo/capacitor-health';
const result = await Health.requestAuthorization({ read: ['steps'] });console.log(result);checkAuthorization
标题为 “checkAuthorization” 的章节无需用户确认即可检查指定数据类型的授权状态。
import { Health } from '@capgo/capacitor-health';
const result = await Health.checkAuthorization({ read: ['steps'] });console.log(result);readSamples
“readSamples” 章节读取指定时间范围内特定数据类型的样本。
import { Health } from '@capgo/capacitor-health';
const result = await Health.readSamples({ dataType: 'steps' });console.log(result);saveSample
“saveSample” 章节将单个样本写入原生健康数据存储。
import { Health } from '@capgo/capacitor-health';
await Health.saveSample({ dataType: 'steps', value: 1,});openHealthConnectSettings
“openHealthConnectSettings” 章节打开 Health Connect 设置界面(仅限 Android)。 在 iOS 上,此方法无效。
用于引导用户管理 Health Connect 权限, 或在未安装时引导其安装 Health Connect。
import { Health } from '@capgo/capacitor-health';
await Health.openHealthConnectSettings();showPrivacyPolicy
“showPrivacyPolicy” 章节显示 Health Connect 的应用隐私政策(仅限 Android)。 在 iOS 上,此方法无效。
这会显示与用户在权限对话框中点击“隐私政策”时 Health Connect 所显示的相同的隐私政策界面。
可以通过在应用的 strings.xml 中添加名为 “health_connect_privacy_policy_url” 的字符串资源来配置隐私政策 URL, 或者在 assets 的 www/privacypolicy.html 路径下放置一个 HTML 文件。
import { Health } from '@capgo/capacitor-health';
await Health.showPrivacyPolicy();queryWorkouts
“queryWorkouts” 章节从原生健康存储中查询运动训练会话。 支持 iOS (HealthKit) 和 Android (Health Connect)。
import { Health } from '@capgo/capacitor-health';
const result = await Health.queryWorkouts({ workoutType: 'americanFootball' });console.log(result);queryAggregated
“queryAggregated” 章节从原生健康存储中查询聚合后的健康数据。 将数据按时间桶(小时、天、周、月)进行聚合,并支持求和、平均值、最小值或最大值等操作。 对于大日期范围,这比获取单个样本更高效。
支持 iOS (HealthKit) 和 Android (Health Connect)。
import { Health } from '@capgo/capacitor-health';
const result = await Health.queryAggregated({ dataType: 'steps' });console.log(result);类型参考
“类型参考” 章节AvailabilityResult
“AvailabilityResult” 章节export interface AvailabilityResult { available: boolean; /** Platform specific details (for debugging/diagnostics). */ platform?: 'ios' | 'android' | 'web'; reason?: string;}AuthorizationOptions
“AuthorizationOptions” 章节export interface AuthorizationOptions { /** Data types that should be readable after authorization. */ read?: HealthDataType[]; /** Data types that should be writable after authorization. */ write?: HealthDataType[]; /** * Android only: request access to health data older than 30 days. * Requires `android.permission.health.READ_HEALTH_DATA_HISTORY` in the manifest. */ requestHistoryAccess?: boolean;}AuthorizationStatus
“AuthorizationStatus” 章节export interface AuthorizationStatus { readAuthorized: HealthDataType[]; readDenied: HealthDataType[]; writeAuthorized: HealthDataType[]; writeDenied: HealthDataType[];}QueryOptions
“QueryOptions” 章节export interface QueryOptions { /** The type of data to retrieve from the health store. */ dataType: HealthDataType; /** Inclusive ISO 8601 start date (defaults to now - 1 day). */ startDate?: string; /** Exclusive ISO 8601 end date (defaults to now). */ endDate?: string; /** Maximum number of samples to return (defaults to 100). */ limit?: number; /** Return results sorted ascending by start date (defaults to false). */ ascending?: boolean;}ReadSamplesResult
“ReadSamplesResult” 章节export interface ReadSamplesResult { samples: HealthSample[];}WriteSampleOptions
“WriteSampleOptions” 章节export interface WriteSampleOptions { dataType: HealthDataType; value: number; /** * Optional 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`). */ unit?: HealthUnit; /** ISO 8601 start date for the sample. Defaults to now. */ startDate?: string; /** ISO 8601 end date for the sample. Defaults to startDate. */ endDate?: string; /** Metadata key-value pairs forwarded to the native APIs where supported. */ metadata?: Record<string, string>; /** For blood pressure data, the systolic value in mmHg. Required when dataType is 'bloodPressure'. */ systolic?: number; /** For blood pressure data, the diastolic value in mmHg. Required when dataType is 'bloodPressure'. */ diastolic?: number;}QueryWorkoutsOptions
“QueryWorkoutsOptions” 章节export interface QueryWorkoutsOptions { /** Optional workout type filter. If omitted, all workout types are returned. */ workoutType?: WorkoutType; /** Inclusive ISO 8601 start date (defaults to now - 1 day). */ startDate?: string; /** Exclusive ISO 8601 end date (defaults to now). */ endDate?: string; /** Maximum number of workouts to return (defaults to 100). */ limit?: number; /** Return results sorted ascending by start date (defaults to false). */ ascending?: boolean; /** * Anchor 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. */ anchor?: string;}QueryWorkoutsResult
“QueryWorkoutsResult” 章节export interface QueryWorkoutsResult { workouts: Workout[]; /** * Anchor 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. */ anchor?: string;}QueryAggregatedOptions
“QueryAggregatedOptions” 章节export interface QueryAggregatedOptions { /** The type of data to aggregate from the health store. */ dataType: HealthDataType; /** Inclusive ISO 8601 start date (defaults to now - 1 day). */ startDate?: string; /** Exclusive ISO 8601 end date (defaults to now). */ endDate?: string; /** Time bucket for aggregation (defaults to 'day'). */ bucket?: BucketType; /** Aggregation operation to perform (defaults to 'sum'). */ aggregation?: AggregationType;}QueryAggregatedResult
“QueryAggregatedResult” 章节export interface QueryAggregatedResult { samples: AggregatedSample[];}HealthDataType
“HealthDataType” 章节export type HealthDataType = | 'steps' | 'distance' | 'calories' | 'heartRate' | 'weight' | 'sleep' | 'respiratoryRate' | 'oxygenSaturation' | 'restingHeartRate' | 'heartRateVariability' | 'bloodPressure' | 'bloodGlucose' | 'bodyTemperature' | 'height' | 'flightsClimbed' | 'exerciseTime' | 'distanceCycling' | 'bodyFat' | 'basalBodyTemperature' | 'basalCalories' | 'totalCalories' | 'mindfulness' | 'workouts';HealthSample
标题为 “HealthSample” 的章节export interface HealthSample { dataType: HealthDataType; value: number; unit: HealthUnit; startDate: string; endDate: string; sourceName?: string; sourceId?: string; /** Platform-specific unique identifier (HealthKit UUID on iOS, Health Connect metadata ID on Android). */ platformId?: string; /** For sleep data, indicates the sleep state (e.g., 'asleep', 'awake', 'rem', 'deep', 'light'). */ sleepState?: SleepState; /** For blood pressure data, the systolic value in mmHg. */ systolic?: number; /** For blood pressure data, the diastolic value in mmHg. */ diastolic?: number;}唯一数据源
“唯一可信来源”章节本页面由该插件的 src/definitions.ts当上游的公共 API 发生变化时,请重新运行 sync。
继续阅读入门指南
标题为“从入门指南继续”的章节如果你正在使用 快速入门 来规划 dashboard 和 API 操作,请将其连接至 使用 @capgo/capacitor-health 用于“使用 @capgo/capacitor-health”中的原生能力, API 概览 关于 API 概览中的实现细节, 简介 有关 Introduction 中的实现细节, API 密钥 有关 API Keys 中的实现细节,以及 设备 有关 Devices 中的实现细节。