跳转至正文

快速入门

GitHub

你可以使用我们的 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-health
bunx 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 以在调用前渲染 UI requestAuthorization 再次尝试。

返回当前平台是否支持原生健康 SDK。

import { Health } from '@capgo/capacitor-health';
const result = await Health.isAvailable();
console.log(result);

请求对所提供数据类型的读/写权限。

import { Health } from '@capgo/capacitor-health';
const result = await Health.requestAuthorization({ read: ['steps'] });
console.log(result);

无需用户确认即可检查指定数据类型的授权状态。

import { Health } from '@capgo/capacitor-health';
const result = await Health.checkAuthorization({ read: ['steps'] });
console.log(result);

读取指定时间范围内特定数据类型的样本。

import { Health } from '@capgo/capacitor-health';
const result = await Health.readSamples({ dataType: 'steps' });
console.log(result);

将单个样本写入原生健康数据存储。

import { Health } from '@capgo/capacitor-health';
await Health.saveSample({
dataType: 'steps',
value: 1,
});

打开 Health Connect 设置界面(仅限 Android)。 在 iOS 上,此方法无效。

用于引导用户管理 Health Connect 权限, 或在未安装时引导其安装 Health Connect。

import { Health } from '@capgo/capacitor-health';
await Health.openHealthConnectSettings();

显示 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();

从原生健康存储中查询运动训练会话。 支持 iOS (HealthKit) 和 Android (Health Connect)。

import { Health } from '@capgo/capacitor-health';
const result = await Health.queryWorkouts({ workoutType: 'americanFootball' });
console.log(result);

从原生健康存储中查询聚合后的健康数据。 将数据按时间桶(小时、天、周、月)进行聚合,并支持求和、平均值、最小值或最大值等操作。 对于大日期范围,这比获取单个样本更高效。

支持 iOS (HealthKit) 和 Android (Health Connect)。

import { Health } from '@capgo/capacitor-health';
const result = await Health.queryAggregated({ dataType: 'steps' });
console.log(result);
export interface AvailabilityResult {
available: boolean;
/** Platform specific details (for debugging/diagnostics). */
platform?: 'ios' | 'android' | 'web';
reason?: string;
}
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;
}
export interface AuthorizationStatus {
readAuthorized: HealthDataType[];
readDenied: HealthDataType[];
writeAuthorized: HealthDataType[];
writeDenied: HealthDataType[];
}
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;
}
export interface ReadSamplesResult {
samples: HealthSample[];
}
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;
}
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;
}
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;
}
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;
}
export interface QueryAggregatedResult {
samples: AggregatedSample[];
}
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';
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 中的实现细节。