android-health-connect
npm GitHub
Docs · Guides

Usage guides

Every flow the library supports, with copy-paste examples. New here? Start with the quickstart, then come back for the details.

01Availability#

Check that Health Connect is usable before calling anything else. ensureAvailable is the one-line gate: it opens the Play Store (or Settings) when Health Connect is missing.

availability.ts
import {
  ensureAvailable,
  isHealthConnectAvailable,
  getHealthConnectAvailability,
  openHealthConnectApp,
  Availability,
} from '@solutionforest/android-health-connect';

// Quick gate: opens the Play Store / Settings when notInstalled (default)
const status = await ensureAvailable();
if (status !== Availability.AVAILABLE) {
  // notInstalled (store opened) | notSupported (hide Health Connect UI)
}

// Or check without side effects
const availability = await isHealthConnectAvailable();
if (availability === Availability.NOT_INSTALLED) {
  openHealthConnectApp(); // Play Store on Android 9–13, Settings on 14+
}

// Details when diagnosing install vs built-in vs no Google Play services
const info = await getHealthConnectAvailability();
// info.provider: 'framework' (Android 14+) | 'apk' (9–13) | 'none'
// info.sdkStatus: 1 = UNAVAILABLE, 2 = PROVIDER_UPDATE_REQUIRED, 3 = AVAILABLE
// info.googlePlayServicesAvailable, info.playStoreAvailable, info.advice
StatusMeaningWhat to do
'available'Installed and readyContinue to permissions
'notInstalled'App missing or needs an updateopenHealthConnectApp()
'notSupported'OS too old, or no Google Play servicesHide Health Connect features

02Device & region notes#

SituationWhat happensWhat to do
Android 14+Health Connect is built into the systemopenHealthConnectSettings()
Android 9–13Health Connect is a Play Store appopenHealthConnectApp() to install or update
sdkStatus === 3Available. This does not mean "version too old"Safe to call the APIs
Mainland China, no Google Play servicesHealth Connect needs Google Play services and is not listed in the CN Play StoreStatus is 'notSupported'; hide the UI
Huawei / HMS without GMSSame as no Google Play servicesNot supported
Samsung / Xiaomi data missingVendor apps must write into Health Connect; this library only reads Health ConnectTurn on Health Connect sharing in the vendor app

03Permissions#

Every permission you request must also be declared in the host app's manifest (the Expo plugin does this from its permissions option). Use the typed Permission.* constants.

permissions.ts
import {
  Permission,
  requestPermissions,
  hasPermissions,
  missingPermissions,
  ensurePermissions,
} from '@solutionforest/android-health-connect';

const needed = [
  Permission.READ_STEPS,
  Permission.WRITE_STEPS,
  Permission.READ_HEART_RATE,
];

// Show the system dialog; returns the granted list
const granted = await requestPermissions(needed);

// Checks without a dialog
if (!(await hasPermissions(needed))) {
  const missing = await missingPermissions(needed);
  console.log('Still missing:', missing);
}

// Or request only what is missing, then re-check
const result = await ensurePermissions(needed);
if (!result.allGranted) {
  console.log('User denied:', result.missing);
}

Denied twice? Android stops showing the dialog. Send the user to openHealthConnectDataManagement() so they can grant access manually.

04History & background reads#

By default Health Connect only lets apps read about 30 days of data before the first grant, and only while the app is in the foreground. Two special permissions lift those limits. Declare them, check the feature, then request.

history.ts
import {
  getFeatureStatus,
  requestPermissions,
  Permission,
  Feature,
  FeatureStatus,
} from '@solutionforest/android-health-connect';
import type { HealthPermission } from '@solutionforest/android-health-connect';

const extra: HealthPermission[] = [];
if ((await getFeatureStatus(Feature.READ_HEALTH_DATA_HISTORY)) === FeatureStatus.AVAILABLE) {
  extra.push(Permission.READ_HEALTH_DATA_HISTORY);
}
if ((await getFeatureStatus(Feature.READ_HEALTH_DATA_IN_BACKGROUND)) === FeatureStatus.AVAILABLE) {
  extra.push(Permission.READ_HEALTH_DATA_IN_BACKGROUND);
}
await requestPermissions([Permission.READ_STEPS, ...extra]);
AndroidManifest.xml
<uses-permission android:name="android.permission.health.READ_HEALTH_DATA_HISTORY" />
<uses-permission android:name="android.permission.health.READ_HEALTH_DATA_IN_BACKGROUND" />

05Read records#

Each record type has a helper (readSteps, readHeartRate, readSleepSessions, …; see all 42). Reads are paged: pass the returned pageToken to get the next page, or use readAllRecords to drain every page.

read.ts
import {
  readSteps,
  readRecords,
  readAllRecords,
  timeRangeLastDays,
  RecordType,
} from '@solutionforest/android-health-connect';
import type { WeightRecord } from '@solutionforest/android-health-connect';

// Typed helper, one page
const { records, pageToken } = await readSteps({
  timeRangeFilter: timeRangeLastDays(7),
  ascendingOrder: true,
  pageSize: 100,
});
records.forEach((r) => console.log(r.count, r.startTime));

// Generic read by record type
const weights = await readRecords<WeightRecord>(RecordType.WEIGHT, {
  timeRangeFilter: timeRangeLastDays(30),
});

// Every page at once
const all = await readAllRecords(RecordType.STEPS, {
  timeRangeFilter: timeRangeLastDays(7),
});
OptionDefaultDescription
timeRangeFilternone{ startTime, endTime } ISO strings, or a timeRange* helper
dataOriginFilterall appsOnly records written by these package names
ascendingOrdertrueOldest first
pageSize1000Maximum records per page
pageTokennoneToken from the previous page

06Write records#

writeRecords inserts a batch of mixed record types and returns the new IDs. Prefer RecordType.* over hand-typed 'Steps' strings. Times use a Carbon-style fluent Instant — now().subMinutes(30) reads like English.

write.ts
import {
  writeRecords,
  RecordType,
  now,
  timeRangeLastHours,
} from '@solutionforest/android-health-connect';

const { startTime, endTime } = timeRangeLastHours(1);
// or: now().subHours(1).until(now())

const { recordIdsList } = await writeRecords([
  {
    recordType: RecordType.STEPS,
    count: 8000,
    startTime,
    endTime,
  },
  {
    recordType: RecordType.WEIGHT,
    weight: 75.5, // kg
    time: now().subMinutes(30).toISOString(),
  },
]);

07Update records#

updateRecords takes the same shape as a write plus metadata.id from a previous read. recordingMethod and device round-trip when they are present on the read record.

update.ts
import {
  readSteps,
  updateRecords,
  RecordingMethod,
} from '@solutionforest/android-health-connect';

const { records } = await readSteps({ timeRangeFilter });
const existing = records[0];
if (!existing?.metadata?.id) throw new Error('nothing to update');

await updateRecords([
  {
    ...existing,
    count: existing.count + 100,
    metadata: {
      ...existing.metadata,
      id: existing.metadata.id,
      recordingMethod:
        existing.metadata.recordingMethod ?? RecordingMethod.MANUAL_ENTRY,
    },
  },
]);

08Delete records#

Delete by time range or by record ID. Apps can only delete records they wrote.

delete.ts
import {
  deleteRecordsByTime,
  deleteRecordsById,
  RecordType,
  now,
} from '@solutionforest/android-health-connect';

// By time range
await deleteRecordsByTime(RecordType.STEPS, now().subDays(1), now());

// By ID
await deleteRecordsById(RecordType.STEPS, ['record-id-1', 'record-id-2']);

09Time ranges#

Range helpers return an Instant TimeRangeFilter for reads, aggregates, and interval writes. Point times use Carbon-style now().subHours(1).toISOString() (or .until(now()) for a window).

HelperReturns
timeRangeToday()Local midnight until now
timeRangeLastDays(n)The last n days until now
timeRangeLastHours(n)The last n hours until now
now()Fluent Instant (Carbon-style)
now().subHours(n)n hours before now
now().subMinutes(n)n minutes before now
now().addDays(n)n days after now
start.until(end){ startTime, endTime }
ranges.ts
import {
  readHeartRate,
  timeRangeLastHours,
} from '@solutionforest/android-health-connect';

const { records } = await readHeartRate({
  timeRangeFilter: timeRangeLastHours(6),
});

10Poll on resume#

Health Connect has no push observer. After the app resumes, the first read is often 0 because Samsung Health, Fitbit, and other apps are still writing. useForegroundPoll polls on mount and on every resume, cancels the in-flight poll when the app goes to the background (so a stale result never overwrites a newer one), and keeps the last value on timeout.

TodaySteps.tsx
import { Text } from 'react-native';
import {
  aggregateRecord,
  timeRangeToday,
  useForegroundPoll,
  RecordType,
} from '@solutionforest/android-health-connect';

const stepsOf = (r: { metrics: Record<string, unknown> }) => {
  const n = r.metrics['COUNT_TOTAL'];
  return typeof n === 'number' ? n : 0;
};

export function TodaySteps({ granted }: { granted: boolean }) {
  const { value, satisfied, loading, error, refresh } = useForegroundPoll(
    () =>
      aggregateRecord({ recordType: RecordType.STEPS, timeRangeFilter: timeRangeToday() }),
    {
      // "> 0" only when you expect activity; a real 0-step day times out
      ready: (r) => stepsOf(r) > 0,
      timeoutMs: 20_000,
      intervalMs: 1_000,
      enabled: granted, // wait until permissions are granted
    },
  );

  if (error) return <Text onPress={refresh}>Couldn't read steps. Tap to retry</Text>;
  return (
    <Text onPress={refresh}>
      {value ? stepsOf(value) : '–'} steps
      {loading ? ' · syncing…' : !satisfied && value ? ' · no new data yet' : ''}
    </Text>
  );
}
OptionDefaultDescription
ready(value)requiredStop polling once this returns true
timeoutMs15000Give up after this long and keep the last value
intervalMs500Delay between polls
enabledtrueSet false to pause, for example until permissions are granted

The hook returns value, satisfied (false when the timeout hit, so it may be a real zero), loading, error, and refresh.

Outside React

pollOnForeground does the same with callbacks and returns { refresh, stop }. For a single wait, use pollUntil (returns { value, satisfied, attempts }) or waitUntil (throws WaitTimeoutError).

poller.ts
import {
  pollOnForeground,
  readSteps,
  timeRangeToday,
} from '@solutionforest/android-health-connect';

const poller = pollOnForeground(
  () => readSteps({ timeRangeFilter: timeRangeToday() }),
  {
    ready: (r) => r.records.length > 0,
    onResult: (r) => store.setSteps(r.records),
    onError: (e) => console.warn(e),
  },
);

// Later, e.g. on logout
poller.stop();

11Wait after writing#

A record you just wrote may not be readable immediately. waitForRecords polls until at least minCount rows come back.

wait.ts
import {
  timeRangeLastDays,
  waitForRecords,
  RecordType,
} from '@solutionforest/android-health-connect';

await waitForRecords({
  recordType: RecordType.STEPS,
  timeRangeFilter: timeRangeLastDays(1),
  minCount: 1,
  timeoutMs: 15_000,
});

12Aggregates#

Health Connect deduplicates overlapping sources in aggregates, so prefer them over summing raw records yourself.

FunctionTime modelUse for
aggregateRecordInstantOne total over a range
aggregateGroupByDurationInstantFixed buckets (hours, minutes). Avoids the Android 14+ UTC wall-clock shift
aggregateGroupByPeriodLocal date-timeCalendar days, weeks, months in the device time zone
aggregates.ts
import {
  aggregateRecord,
  aggregateGroupByDuration,
  timeRangeLastDays,
  RecordType,
  now,
} from '@solutionforest/android-health-connect';

const total = await aggregateRecord({
  recordType: RecordType.STEPS,
  timeRangeFilter: timeRangeLastDays(7),
});
console.log(total.metrics['COUNT_TOTAL']); // number | null

const hourly = await aggregateGroupByDuration({
  recordType: RecordType.STEPS,
  timeRangeFilter: now().subDays(1).until(now()),
  timeRangeSlicer: { unit: 'hours', value: 1 },
});
hourly.forEach((row) => {
  console.log(row.startTime, row.result.metrics['COUNT_TOTAL']);
});

13Changelog sync#

Sync only what changed since last time. Tokens expire after about 30 days; use one record type per token. When changesTokenExpired is true, backfill with a normal read and mint a new token. pageSize (1–5000) is a soft hint.

sync.ts
import {
  getChangesToken,
  pullChanges,
  RecordType,
} from '@solutionforest/android-health-connect';

let token = await getChangesToken({ recordTypes: [RecordType.STEPS] });

// ...later
const batch = await pullChanges(token, { pageSize: 500 });
if (batch.changesTokenExpired) {
  // backfill with readRecords, then mint a fresh token
  token = await getChangesToken({ recordTypes: [RecordType.STEPS] });
} else {
  for (const { record } of batch.upsertionChanges) {
    console.log('upsert', record.recordType, record.metadata?.id);
  }
  for (const { recordId } of batch.deletionChanges) {
    console.log('delete', recordId);
  }
  token = batch.nextChangesToken; // persist for the next sync
}

14React hooks#

Typed hooks wrap the imperative API. Each one fetches on mount, fetches again whenever the app returns to the foreground (built on pollOnForeground), refetches when its arguments change (compared by value, so inline arrays and objects are fine), and drops results that arrive after unmount or for older arguments.

Dashboard.tsx
import { Button, Text } from 'react-native';
import {
  Permission,
  RecordType,
  timeRangeLastDays,
  timeRangeToday,
  useAggregate,
  useHealthConnectAvailability,
  useHealthConnectPermissions,
  useMostRecentRecord,
  useReadRecords,
  type StepsRecord,
  type WeightRecord,
} from '@solutionforest/android-health-connect';

export function Dashboard() {
  const availability = useHealthConnectAvailability();
  const [perms, request] = useHealthConnectPermissions([
    Permission.READ_STEPS,
    Permission.READ_WEIGHT,
  ]);
  const ready =
    availability.value === 'available' && perms.value?.allGranted === true;

  // Pass a function for "now"-relative ranges: it is re-evaluated on every
  // fetch and does not restart the query on re-render.
  const today = useAggregate(RecordType.STEPS, () => timeRangeToday(), { enabled: ready });
  const week = useReadRecords<StepsRecord>(RecordType.STEPS, {
    timeRangeFilter: () => timeRangeLastDays(7),
    enabled: ready,
  });
  const weight = useMostRecentRecord<WeightRecord>(RecordType.WEIGHT, {
    enabled: ready,
  });

  if (availability.value !== 'available') return <Text>Install Health Connect</Text>;
  if (!perms.value?.allGranted) {
    return <Button title="Allow access" onPress={() => void request()} />;
  }
  return (
    <Text>
      {String(today.value?.metrics['COUNT_TOTAL'] ?? '–')} steps today ·{' '}
      {week.value?.records.length ?? 0} step records this week ·{' '}
      {weight.value ? `${weight.value.weight} kg` : 'no weight'}
    </Text>
  );
}
HookvalueNotes
useHealthConnectAvailability(opts?)'available' | 'notInstalled' | 'notSupported'Updates after the user installs Health Connect and comes back
useHealthConnectPermissions(perms, opts?)[status, request]; status.value is { granted, missing, allGranted }request() shows the dialog for missing permissions only and resolves with the re-checked result
useReadRecords<T>(type, opts?)ReadRecordsResponse<T>Same options as readRecords; timeRangeFilter may be a function
useMostRecentRecord<T>(type, opts?)T | nullNewest record in the window (default: last 30 days)
useAggregate(type, range, opts?)AggregateResultrange may be a function, such as () => timeRangeToday()
useChanges(token, opts?)PullChangesResultChangelog sync that continues from nextChangesToken

The data hooks return { value, satisfied, loading, error, refresh }, the same shape as useForegroundPoll, and accept enabled, ready, timeoutMs and intervalMs. Without ready, each fetch is a single read. Add ready to keep polling through the "0 right after resume" gap:

steps.ts
const steps = useAggregate(RecordType.STEPS, () => timeRangeToday(), {
  ready: (r) => ((r.metrics['COUNT_TOTAL'] as number | null) ?? 0) > 0,
  timeoutMs: 20_000,
});
// steps.satisfied === false → timed out; the value may be a real 0

Changelog sync with useChanges

useChanges(token, { onChanges }) drains the changelog with pullChanges on mount and on every resume. After each pull it continues from nextChangesToken, so persist that token in onChanges. Pass null to pause until you have a token. When changesTokenExpired is true, backfill and pass a fresh token from getChangesToken; a new token restarts from it.

useStepsSync.ts
const [token, setToken] = useState<string | null>(storedToken);
useChanges(token, {
  onChanges: ({ upsertionChanges, deletionChanges, nextChangesToken, changesTokenExpired }) => {
    if (changesTokenExpired) {
      void backfill().then(() =>
        getChangesToken({ recordTypes: [RecordType.STEPS] }).then(setToken),
      );
      return;
    }
    applyToLocalDb(upsertionChanges, deletionChanges);
    saveToken(nextChangesToken);
  },
});

15Exercise routes#

Writing a route with a session needs WRITE_EXERCISE_ROUTE; reading routes from other apps needs READ_EXERCISE_ROUTES. On read, a route is DATA, NO_DATA, or CONSENT_REQUIRED. Leave out optional altitude and accuracy fields rather than sending empty objects.

routes.ts
import {
  writeRecords,
  readExerciseSessions,
  requestExerciseRoute,
  getFeatureStatus,
  ExerciseType,
  RecordType,
  Feature,
  FeatureStatus,
  now,
  timeRangeLastDays,
} from '@solutionforest/android-health-connect';

const end = now();
const start = end.subHours(1);
const mid = end.subMinutes(30);

await writeRecords([
  {
    recordType: RecordType.EXERCISE_SESSION,
    exerciseType: ExerciseType.RUNNING,
    startTime: start.toISOString(),
    endTime: end.toISOString(),
    exerciseRoute: {
      route: [
        { time: start.toISOString(), latitude: 51.5, longitude: -0.12, altitude: 19 },
        { time: mid.toISOString(), latitude: 51.51, longitude: -0.11 },
      ],
    },
  },
]);

// Optional 1.2 fields, behind a feature check
if ((await getFeatureStatus(Feature.EXERCISE_SESSION_IMPROVEMENTS)) === FeatureStatus.AVAILABLE) {
  await writeRecords([
    {
      recordType: RecordType.EXERCISE_SESSION,
      exerciseType: ExerciseType.RUNNING,
      startTime: start.toISOString(),
      endTime: end.toISOString(),
      rateOfPerceivedExertion: 6.5,
    },
  ]);
}

const { records } = await readExerciseSessions({
  timeRangeFilter: timeRangeLastDays(7),
});
for (const session of records) {
  const route = session.exerciseRoute;
  if (!route || route.type === 'NO_DATA') continue;
  if (route.type === 'CONSENT_REQUIRED') {
    const granted = await requestExerciseRoute(session.metadata?.id ?? '');
    console.log(granted?.route);
  } else {
    console.log(route.route);
  }
}

16Planned exercise#

Training plans need getFeatureStatus(Feature.PLANNED_EXERCISE) === FeatureStatus.AVAILABLE, plus READ_PLANNED_EXERCISE / WRITE_PLANNED_EXERCISE.

plan.ts
import {
  requestPermissions,
  writeRecords,
  readPlannedExerciseSessions,
  ExerciseType,
  ExerciseSegmentType,
  ExercisePhase,
  Permission,
  RecordType,
  now,
} from '@solutionforest/android-health-connect';

await requestPermissions([
  Permission.READ_PLANNED_EXERCISE,
  Permission.WRITE_PLANNED_EXERCISE,
]);

const start = now().addDays(2);
const end = start.addMinutes(90);

await writeRecords([
  {
    recordType: RecordType.PLANNED_EXERCISE_SESSION,
    exerciseType: ExerciseType.RUNNING,
    startTime: start.toISOString(),
    endTime: end.toISOString(),
    title: 'Lake run',
    blocks: [
      {
        repetitions: 1,
        description: 'Three laps',
        steps: [
          {
            exerciseType: ExerciseSegmentType.RUNNING,
            exercisePhase: ExercisePhase.ACTIVE,
            completionGoal: { type: 'Repetitions', repetitions: 3 },
            performanceTargets: [
              { type: 'HeartRate', minHeartRate: 90, maxHeartRate: 110 },
            ],
          },
        ],
      },
    ],
  },
]);

const plans = await readPlannedExerciseSessions({
  timeRangeFilter: now().until(now().addDays(14)),
});

17Matchmaking & PHR#

Newer Health Connect features are not on every device. Always check getFeatureStatus(Feature.*) first. It returns FeatureStatus.AVAILABLE or FeatureStatus.UNAVAILABLE.

Feature keyUnlocks
skinTemperatureSkinTemperature records
mindfulnessSessionMindfulnessSession records
activityIntensityActivityIntensity records
plannedExercisePlannedExerciseSession records
exerciseSessionImprovementsRPE and plannedExerciseSessionId on sessions
readHealthDataHistoryReads older than 30 days
readHealthDataInBackgroundReads while backgrounded
extendedDeviceTypesAdditional device type values in record metadata
matchmakingDiscover apps and devices that can write data you read
personalHealthRecordFHIR medical data sources and resources
features.ts
import {
  getFeatureStatus,
  checkIfMatchmakingIsPossible,
  launchMatchmaking,
  createMedicalDataSource,
  upsertMedicalResources,
  readMedicalResources,
  MedicalResourceType,
  RecordType,
  Feature,
  FeatureStatus,
  FhirVersion,
} from '@solutionforest/android-health-connect';

// Matchmaking (experimental)
if ((await getFeatureStatus(Feature.MATCHMAKING)) === FeatureStatus.AVAILABLE) {
  const { isMatchmakingPossible } = await checkIfMatchmakingIsPossible({
    recordTypes: [RecordType.STEPS, RecordType.HEART_RATE],
  });
  if (isMatchmakingPossible) {
    await launchMatchmaking({ recordTypes: [RecordType.STEPS, RecordType.HEART_RATE] });
  }
}

// Personal Health Record (experimental): FHIR data source + resources
if ((await getFeatureStatus(Feature.PERSONAL_HEALTH_RECORD)) === FeatureStatus.AVAILABLE) {
  const source = await createMedicalDataSource({
    displayName: 'Clinic FHIR',
    fhirBaseUri: 'https://example.com/fhir/',
    fhirVersion: FhirVersion.R4,
  });
  await upsertMedicalResources([
    {
      dataSourceId: source.id,
      fhirVersion: source.fhirVersion,
      data: JSON.stringify({ resourceType: 'AllergyIntolerance', id: '1' }),
    },
  ]);
  const page = await readMedicalResources({
    medicalResourceType: MedicalResourceType.ALLERGIES_INTOLERANCES,
    medicalDataSourceIds: [source.id],
  });
}

18Upgrade reminders#

checkLibraryUpdate compares the installed version with the latest GitHub Release, so you can show a banner in debug builds.

update.ts
import {
  checkLibraryUpdate,
  LIBRARY_VERSION,
} from '@solutionforest/android-health-connect';

const update = await checkLibraryUpdate();
if (update.updateAvailable) {
  console.warn(update.advice); // update.currentVersion → update.latestVersion
}

19Common mistakes#

SymptomCauseFix
Permission dialog never showsPermission not declared in the host manifestAdd it to AndroidManifest.xml or the Expo plugin's permissions
Steps show 0 right after opening the appOther apps are still syncinguseForegroundPoll with a ready check
updateRecords failsMissing metadata.idRead the record first and keep its metadata
Day totals off by hours on Android 14+Calendar math done with Instant bucketsUse aggregateGroupByPeriod for calendar days
Changelog returns nothing after weeksToken older than about 30 daysHandle changesTokenExpired: backfill, then new token
Crash on a newer APIFeature missing on the deviceGate on getFeatureStatus
Build fails resolving the moduleOld Architecture or RN below 0.84Enable New Architecture; use RN 0.84+
Gradle or AGP errorsWrong release line for the toolchain0.3.x needs AGP 9.1+; otherwise use release-0.2

Next: browse all record types or the API reference.