跳转到正文

快速入门

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 根据结果决定是否显示设置深度链接。

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 在调用前渲染 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 上,此方法不执行任何操作。

它会显示与用户在权限对话框中点击“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();

从原生健康存储中查询锻炼会话。 支持 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 Overview 中的实现细节, 简介 关于 Introduction 中的实现细节, API 密钥 有关 API Keys 的实现细节,以及 设备 有关 Devices 的实现细节。