快速入门
复制包含安装步骤和该插件完整 Markdown 指南的配置 prompt。
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 根据结果决定是否显示设置深度链接。
示例:记录一条体重样本
标题为“示例:记录体重样本”的章节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 安装状态:使用
isAvailable以及openHealthConnectSettings当提供方缺失或被禁用时。 - 历史记录权限仅限 Android:在 iOS 上会被忽略,因为 iOS 不使用 30 天上限。
- 提示前检查:使用
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 上,此方法不执行任何操作。
它会显示与用户在权限对话框中点击“Privacy policy”时 Health Connect 展示的相同的隐私政策页面。
可以通过在应用的 strings.xml 中添加名为 “health_connect_privacy_policy_url” 的字符串资源来配置隐私政策 URL,或者将 HTML 文件放到 assets 中的 www/privacypolicy.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 Overview 中的实现细节, 简介 关于 Introduction 中的实现细节, API 密钥 有关 API Keys 的实现细节,以及 设备 有关 Devices 的实现细节。