メインコンテンツへスキップ

はじめに

GitHub

AIアシストセットアップを使ってプラグインをインストールできます。以下のコマンドで、お使いのAIツールに Capgo スキルを追加してください:

ターミナルウィンドウ
npx skills add https://github.com/Cap-go/capgo-skills --skill capacitor-plugins

次に、以下のプロンプトを使用します:

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

クイックスタート

「Quick start」セクション

利用可能状況を確認し、必要なタイプへの読み取り権限をリクエストしてから、日付範囲を指定してクエリを実行します。

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;
}

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など)。

よくある落とし穴

「Common pitfalls」セクション
  • 認証はデータタイプごとに行われます: 毎回リクエスト HealthDataType 事前に読み書きが必要なもの。
  • Android Health Connect のインストール状態: 使用 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が表示するのと同じプライバシーポリシー画面を表示します。

プライバシーポリシーのURLは、アプリのstrings.xmlに「health_connect_privacy_policy_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 を実行してください。

以下を使用している場合: はじめに ダッシュボードと API の操作を計画するには、以下と連携してください @capgo/capacitor-health の使用方法 Using @capgo/capacitor-health 内のネイティブ機能として、 API の概要 API Overview の実装の詳細については、 はじめに Introduction の実装の詳細については、 API キー API Keys の実装の詳細については、 デバイス Devices の実装の詳細については。