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.
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
| Status | Meaning | What to do |
|---|---|---|
'available' | Installed and ready | Continue to permissions |
'notInstalled' | App missing or needs an update | openHealthConnectApp() |
'notSupported' | OS too old, or no Google Play services | Hide Health Connect features |
02Device & region notes#
| Situation | What happens | What to do |
|---|---|---|
| Android 14+ | Health Connect is built into the system | openHealthConnectSettings() |
| Android 9–13 | Health Connect is a Play Store app | openHealthConnectApp() to install or update |
sdkStatus === 3 | Available. This does not mean "version too old" | Safe to call the APIs |
| Mainland China, no Google Play services | Health Connect needs Google Play services and is not listed in the CN Play Store | Status is 'notSupported'; hide the UI |
| Huawei / HMS without GMS | Same as no Google Play services | Not supported |
| Samsung / Xiaomi data missing | Vendor apps must write into Health Connect; this library only reads Health Connect | Turn 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.
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.
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]);
<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.
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),
});
| Option | Default | Description |
|---|---|---|
timeRangeFilter | none | { startTime, endTime } ISO strings, or a timeRange* helper |
dataOriginFilter | all apps | Only records written by these package names |
ascendingOrder | true | Oldest first |
pageSize | 1000 | Maximum records per page |
pageToken | none | Token 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.
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.
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.
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).
| Helper | Returns |
|---|---|
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 } |
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.
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>
);
}
| Option | Default | Description |
|---|---|---|
ready(value) | required | Stop polling once this returns true |
timeoutMs | 15000 | Give up after this long and keep the last value |
intervalMs | 500 | Delay between polls |
enabled | true | Set 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).
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.
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.
| Function | Time model | Use for |
|---|---|---|
aggregateRecord | Instant | One total over a range |
aggregateGroupByDuration | Instant | Fixed buckets (hours, minutes). Avoids the Android 14+ UTC wall-clock shift |
aggregateGroupByPeriod | Local date-time | Calendar days, weeks, months in the device time zone |
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.
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.
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>
);
}
| Hook | value | Notes |
|---|---|---|
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 | null | Newest record in the window (default: last 30 days) |
useAggregate(type, range, opts?) | AggregateResult | range may be a function, such as () => timeRangeToday() |
useChanges(token, opts?) | PullChangesResult | Changelog 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:
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.
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.
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.
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 key | Unlocks |
|---|---|
skinTemperature | SkinTemperature records |
mindfulnessSession | MindfulnessSession records |
activityIntensity | ActivityIntensity records |
plannedExercise | PlannedExerciseSession records |
exerciseSessionImprovements | RPE and plannedExerciseSessionId on sessions |
readHealthDataHistory | Reads older than 30 days |
readHealthDataInBackground | Reads while backgrounded |
extendedDeviceTypes | Additional device type values in record metadata |
matchmaking | Discover apps and devices that can write data you read |
personalHealthRecord | FHIR medical data sources and resources |
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.
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#
| Symptom | Cause | Fix |
|---|---|---|
| Permission dialog never shows | Permission not declared in the host manifest | Add it to AndroidManifest.xml or the Expo plugin's permissions |
| Steps show 0 right after opening the app | Other apps are still syncing | useForegroundPoll with a ready check |
updateRecords fails | Missing metadata.id | Read the record first and keep its metadata |
| Day totals off by hours on Android 14+ | Calendar math done with Instant buckets | Use aggregateGroupByPeriod for calendar days |
| Changelog returns nothing after weeks | Token older than about 30 days | Handle changesTokenExpired: backfill, then new token |
| Crash on a newer API | Feature missing on the device | Gate on getFeatureStatus |
| Build fails resolving the module | Old Architecture or RN below 0.84 | Enable New Architecture; use RN 0.84+ |
| Gradle or AGP errors | Wrong release line for the toolchain | 0.3.x needs AGP 9.1+; otherwise use release-0.2 |
Next: browse all record types or the API reference.