Health Connect
If you are interested in configure and use Apple Health and Health Connect (Android) we highly recommend to refer to Rook SDK
This SDK enables apps to extract and upload data from Health Connect, with this sdk you will be able to extract and upload data from health connect, if you need check our app demo
Installation
To build a project using the Rook Health Connect in React native you need to use at least react v16 and react native v65. This SDK is only available on Android this means that it won't work with iOS.
The minimum version of android sdk is 26, the target sdk 34 and the kotlin version >= 1.8.10
npm
npm i react-native-rook-sdk-health-connect
yarn
yarn add react-native-rook-sdk-health-connect
Configuration
Add your client uuid in order to be authorized, follow the next example, add at the top level of your tree components the RookConnectProvider, password refers to the secret key.
import { RookSyncGate } from "react-native-rook-sdk-health-connect";
<RookSyncGate
environment="sandbox | production"
clientUUID="YOUR_CLIENT_UUID"
password="YOUR_PASSWORD"
enableLogs={true | false | undefined}
enableBackgroundSync={true | false}
>
<YOUR_COMPONENTS />
</RookSyncGate>;
Then we need to configure the android project. open the android project inside android studio. We need to modify the AndroidManifest.xml file in order to access to the Health connection records.
We need to add inside your activity tag an intent filter to open Health Connect APP and your AndroidManifest.xml
file should look like this
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
...
<application
...>
<activity
...>
<intent-filter>
...
</intent-filter>
<!-- For supported versions through Android 13, create an activity to show the rationale
of Health Connect permissions once users click the privacy policy link. -->
<intent-filter>
<action android:name="androidx.health.ACTION_SHOW_PERMISSIONS_RATIONALE" />
</intent-filter>
</activity>
<!-- For versions starting Android 14, create an activity alias to show the rationale
of Health Connect permissions once users click the privacy policy link. -->
<activity-alias
android:name="ViewPermissionUsageActivity"
android:exported="true"
android:permission="android.permission.START_VIEW_PERMISSION_USAGE"
android:targetActivity=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.VIEW_PERMISSION_USAGE" />
<category android:name="android.intent.category.HEALTH_PERMISSIONS" />
</intent-filter>
</activity-alias>
</application>
</manifest>
Included permissions
This SDK will use the following permissions, there is no need to declare them in your manifest as the rook-sdk already declares them in its own manifest:
<uses-permission android:name="android.permission.ACTIVITY_RECOGNITION"/>
<uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_HEALTH"/>
<uses-permission android:name="android.permission.POST_NOTIFICATIONS"/>
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<uses-permission android:name="android.permission.health.READ_SLEEP"/>
<uses-permission android:name="android.permission.health.READ_STEPS"/>
<uses-permission android:name="android.permission.health.READ_DISTANCE"/>
<uses-permission android:name="android.permission.health.READ_FLOORS_CLIMBED"/>
<uses-permission android:name="android.permission.health.READ_ELEVATION_GAINED"/>
<uses-permission android:name="android.permission.health.READ_OXYGEN_SATURATION"/>
<uses-permission android:name="android.permission.health.READ_VO2_MAX"/>
<uses-permission android:name="android.permission.health.READ_TOTAL_CALORIES_BURNED"/>
<uses-permission android:name="android.permission.health.READ_ACTIVE_CALORIES_BURNED"/>
<uses-permission android:name="android.permission.health.READ_HEART_RATE"/>
<uses-permission android:name="android.permission.health.READ_RESTING_HEART_RATE"/>
<uses-permission android:name="android.permission.health.READ_HEART_RATE_VARIABILITY"/>
<uses-permission android:name="android.permission.health.READ_EXERCISE"/>
<uses-permission android:name="android.permission.health.READ_SPEED"/>
<uses-permission android:name="android.permission.health.READ_WEIGHT"/>
<uses-permission android:name="android.permission.health.READ_HEIGHT"/>
<uses-permission android:name="android.permission.health.READ_BLOOD_GLUCOSE"/>
<uses-permission android:name="android.permission.health.READ_BLOOD_PRESSURE"/>
<uses-permission android:name="android.permission.health.READ_HYDRATION"/>
<uses-permission android:name="android.permission.health.READ_BODY_TEMPERATURE"/>
<uses-permission android:name="android.permission.health.READ_RESPIRATORY_RATE"/>
<uses-permission android:name="android.permission.health.READ_NUTRITION"/>
<uses-permission android:name="android.permission.health.READ_MENSTRUATION"/>
<uses-permission android:name="android.permission.health.READ_POWER"/>
Google may require you to provide an explanation about the FOREGROUND_SERVICE
/FOREGROUND_SERVICE_HEALTH
permissions,
these permissions are used by our Automatic Sync and Background Steps features, to extract health data and upload it to ROOK servers. We
recommend you to ask users for permission before enabling these features (Google may also require a video proof of a
screen where a user can turn on/off these features).
Request data access
When you are developing with the Health Connect SDK data access is unrestricted. In order to have data access when your app is launched to the PlayStore you MUST complete the Developer Declaration Form, more information Here.
When you are asked about what data types is your app using please add the following data types as READ access:
- ActiveCaloriesBurnedRecord
- BloodGlucoseRecord
- BloodPressureRecord
- BodyTemperatureRecord
- DistanceRecord
- ElevationGainedRecord
- ExerciseSessionRecord
- FloorsClimbedRecord
- HeartRateRecord
- HeartRateVariabilityRmssdRecord
- HeightRecord
- HydrationRecord
- MenstruationPeriodRecord
- NutritionRecord
- OxygenSaturationRecord
- PowerRecord
- RespiratoryRateRecord
- RestingHeartRateRecord
- SleepSessionRecord
- SpeedRecord
- StepsCadenceRecord
- StepsRecord
- TotalCaloriesBurnedRecord
- Vo2MaxRecord
- WeightRecord
Obfuscation
If you are using obfuscation consider the following:
In your proguard-rules.pro add the following rule:
-keep class com.google.crypto.** { *; }
In your gradle.properties (Project level) add the following to disable R8 full mode:
android.enableR8.fullMode=false
If you want to enable full mode add the following rules to proguard-rules.pro:
# Keep generic signature of Call, Response (R8 full mode strips signatures from non-kept items).
-keep,allowobfuscation,allowshrinking interface retrofit2.Call
-keep,allowobfuscation,allowshrinking class retrofit2.Response
# With R8 full mode generic signatures are stripped for classes that are not
# kept. Suspend functions are wrapped in continuations where the type argument
# is used.
-keep,allowobfuscation,allowshrinking class kotlin.coroutines.Continuation
# Crypto
-keep class com.google.crypto.** { *; }
Usage
useRookSyncConfiguration
This hook will help you to configure the user ID you want to sync.
The updateUserID should be called as a part of your Log in flow, when your users log out from your app call clearUserID (this is optional as any call to updateUserID will override the previous userID).
import { useRookSyncConfiguration } from "react-native-rook-sdk-health-connect";
type DoOnEnd = 'oldest' | 'latest' | 'nothing';
const useRookSyncConfiguration = () => {
ready: boolean;
getUserID: () => Promise<string>;
updateUserID: (userID: string) => Promise<boolean>;
clearUserID: () => Promise<boolean>;
syncUserTimeZone: () => Promise<boolean>;
deleteUserFromRook: () => Promise<boolean>;
scheduleYesterdaySync: (doOnEnd?: DoOnEnd) => Promise<boolean>;
}
ready
: Indicates when the hook is ready to work.getUserID
: Return the current user ID.updateUserID
: Change the current user ID.clearUserID
: Clear the current user ID.syncUserTimeZone
: Update the time zone of the user, you should only call this when is strictly necessary.deleteUserFromRook
: Delete the user from the Rook services.scheduleYesterdaySync
: The functionscheduleYesterdaySync
is an asynchronous function that syncs data of the different summaries and events that Rook has. We have three options for sync:- oldest: After syncing yesterday data, subsequent syncs should start from the 29th day until the 2nd day (The day before yesterday).
- latest: After syncing yesterday data, subsequent syncs should start from the 2nd day (The day before yesterday) day until the 29th.
- nothing: Only sync yesterday data (Default).
Note: If you delete the user from the Rook services you have to create the user again with updateUserID
and request permissions.
Any call to updateUserID
the userID will override the previous userID and reset the sync status, so if you are using background sync all health data will synchronize again the next time the app is launched.
useRookSyncPermissions
This hook will help you to request permissions to extract data. Before proceeding further, you need to ensure the user’s device is compatible with Health Connect and check if the APK is installed.
import { useRookSyncPermissions } from "react-native-rook-sdk-health-connect";
export type Availability = "INSTALLED" | "NOT_INSTALLED" | "NOT_SUPPORTED";
export type RequestStatusPermissions = "REQUEST_SENT" | "ALREADY_GRANTED";
const useRookSyncPermissions: () => {
ready: boolean;
checkAvailability: () => Promise<Availability>;
openHealthConnectSettings: () => Promise<void>;
checkPermissions: () => Promise<void>;
shouldRequestAndroidBackgroundPermissions: () => Promise<boolean>;
requestPermissions: () => Promise<RequestStatusPermissions>;
requestAndroidBackgroundPermissions: () => Promise<RequestStatusPermissions>;
hasAndroidBackgroundPermissions: () => Promise<boolean>;
};
ready
: Indicates when the hook is ready to work.checkAvailability
: Check if the health connect service is available.openHealthConnectSettings
: Open the health connect settings.checkPermissions
: Check if the sdk have the permissions to read data from health connect.shouldRequestAndroidBackgroundPermissions
: Check if is necessary to request background permissionsrequestPermissions
: Request the permissions for health connect, return two possible valuesREQUEST_SENT
means that the view requesting permissions was shown orALREADY_GRANTED
means that the user is allowed to request permissions.requestAndroidBackgroundPermissions
: Request the permissions for enable background sync, return two possible valuesREQUEST_SENT
means that the alerts requesting permissions was shown orALREADY_GRANTED
means that the user is allowed to request permissions.hasAndroidBackgroundPermissions
: Check if the app has permissions to access the background services
useRookSyncSummaries
This hook will help you to extract and send data from health connect to Rook servers.
import { useRookSyncSummaries } from "react-native-rook-sdk-health-connect";
const useRookSyncSummaries: () => {
ready: boolean;
syncYesterdaySummaries: () => Promise<void>;
shouldSyncSleepSummariesFor: (date: string) => Promise<boolean>;
syncSleepSummary: (date: string) => Promise<boolean>;
shouldSyncBodySummariesFor: (date: string) => Promise<boolean>;
syncBodySummary: (date: string) => Promise<boolean>;
shouldSyncPhysicalSummariesFor: (date: string) => Promise<boolean>;
syncPhysicalSummary: (date: string) => Promise<boolean>;
syncPendingSummaries: () => Promise<boolean>;
};
ready
: Indicates when the hook is ready to work.shouldSyncSleepSummariesFor
: Verify if you have summaries to sync in a specific date.syncSleepSummary
: Send the summary to rook servers.shouldSyncBodySummariesFor
: Verify if you have summaries to sync in a specific date.syncBodySummary
: Send the summary to rook servers.shouldSyncPhysicalSummariesFor
: Verify if you have summaries to sync in a specific date.syncPhysicalSummary
: Send the summary to rook servers.syncPendingSummaries
: In case you try to sync a summary and fail, this function help to try to send again.
useRookSyncEvents
This hook will help you to extract and send data from health connect to Rook servers.
import { useRookSyncEvents } from "react-native-rook-sdk-health-connect";
const useRookSyncEvents: () => {
ready: boolean;
syncYesterdayEvents: () => Promise<void>;
syncPhysicalEvents: (date: string) => Promise<boolean>;
syncBloodGlucoseEvents: (date: string) => Promise<boolean>;
syncBloodPressureEvents: (date: string) => Promise<boolean>;
syncBodyMetricsEvents: (date: string) => Promise<boolean>;
syncBodyHeartRateEvents: (date: string) => Promise<boolean>;
syncPhysicalHeartRateEvents: (date: string) => Promise<boolean>;
syncHydrationEvents: (date: string) => Promise<boolean>;
syncNutritionEvents: (date: string) => Promise<boolean>;
syncBodyOxygenationEvents: (date: string) => Promise<boolean>;
syncPhysicalOxygenationEvents: (date: string) => Promise<boolean>;
syncTemperatureEvents: (date: string) => Promise<boolean>;
syncPendingEvents: () => Promise<boolean>;
};
ready
: Indicates when the hook is ready to work.syncPhysicalEvents
: Send physical events for the specified date.syncBloodGlucoseEvents
: Send blood glucose events for the specified date.syncBloodPressureEvents
: Send blood pressure events for the specified date.syncBodyMetricsEvents
: Send body metrics events for the specified date.syncBodyHeartRateEvents
: Send body heart rate events for the specified date.syncPhysicalHeartRateEvents
: Send physical heart rate events for the specified date.syncHydrationEvents
: Send hydration rate events for the specified date.syncNutritionEvents
: Send nutrition events for the specified date.syncBodyOxygenationEvents
: Send body oxygenation events for the specified date.syncPhysicalOxygenationEvents
: Send physical oxygenation events for the specified date.syncTemperatureEvents
: Send temperature events for the specified date.syncPendingEvents
: In case you try to sync an event and fail, this function help to try to send again.
useRookDataSources
This hook enables you to access available ROOK data sources by requesting a JSON object with the information or by displaying a basic view with a set of buttons.
import { useRookDataSources } from "react-native-rook-sdk-health-connect";
export interface DataSource {
name: string;
authorizationURL: string;
imageUrl: string;
description: string;
connected: boolean;
}
type options = {
redirectURL?: string;
};
export type DataSourceType =
| "Garmin"
| "Oura"
| "Polar"
| "Fitbit"
| "Withings"
| "Whoop";
const useRookDataSources: () => {
ready: boolean;
getAvailableDataSources: (options?: options) => Promise<DataSource[]>;
presentDataSourcesView: (options?: options) => Promise<boolean>;
revokeDataSource: (type: DataSourceType) => Promise<boolean>;
};
ready
: Indicates when the hook is ready to work.getAvailableDataSources
: Return a list of available data sources, with the ability to configure with the options parampresentDataSourceView
: Present a default view with the available data sources, with the ability to configure with the options paramrevokeDataSource
: Revokes user authorization for the specified data source.
useRookBackgroundSteps
This hook will help you to extract and send data from health connect to Rook servers.
import { useRookBackgroundSteps } from "react-native-rook-sdk-health-connect";
const useRookBackgroundSteps: () => {
ready: boolean;
isStepsAvailable: () => Promise<boolean>;
hasStepsPermissions: () => Promise<boolean>;
requestStepsPermissions: () => Promise<boolean>;
enableBackgroundAndroidSteps: () => Promise<boolean>;
disableBackgroundAndroidSteps: () => Promise<boolean>;
isBackgroundAndroidStepsActive: () => Promise<boolean>;
syncTodayAndroidStepsCount: () => Promise<boolean>;
};
ready
: Indicates when the hook is ready to work.isStepsAvailable
: Verify if the device has this functionality.hasStepsPermissions
: Verify if the user gave permissions to get the steps.requestStepsPermissions
: This function is deprecated and it will be removed in next versions, please use insteaduseRookSyncPermissions().requestAndroidBackgroundPermissions()
- Request permissions to get the steps.enableBackgroundAndroidSteps
: Start the service for get the steps, and collect all the steps for one hour then the total count will be send to rook servers.disableBackgroundAndroidSteps
: Stop the service for get the steps.isBackgroundAndroidStepsActive
: Verify if the steps are active.syncTodayAndroidStepsCount
: Get the steps from the current day from the android steps system.syncTodayHealthConnectStepsCount
: Get the steps from the current day from Health Connect.
Additional notes
In order to include correctly the steps services follow this steps:
- Request Permissions
- Enable background Android steps
- Sync Steps
Customizing the foreground service notification
The steps manager uses a foreground Service which requires a notification to be permanently displayed.
To use your own resources you need to reference them in the AndroidManifest.xml file:
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<application>
<meta-data
android:name="io.tryrook.service.notification.STEPS_ICON"
android:resource="@drawable/my_custom_icon"/>
<meta-data
android:name="io.tryrook.service.notification.STEPS_TITLE"
android:resource="@string/my_custom_title"/>
<meta-data
android:name="io.tryrook.service.notification.STEPS_CONTENT"
android:resource="@string/my_custom_content"/>
</application>
</manifest>
Starting on Android 13 (SDK 33) this notification can be dismissed without finishing the service associated with it, then the service will be displayed in the active apps section (This may vary depending on device brand).
Sync health data automatically
To automatically sync health data, use the scheduleYesterdaySync
function during your app's initialization phase. We highly recommend checking and saving whether the user has explicitly given you permission to sync data automatically. In this example, we use @react-native-async-storage/async-storage
to achieve this.
import React, { useEffect } from "react";
import { View } from "react-native";
import AsyncStorage from "@react-native-async-storage/async-storage";
import { useRookSyncConfiguration } from "react-native-rook-sdk-health-connect";
function MyComponent() {
const { scheduleYesterdaySync } = useRookSyncConfiguration();
useEffect(() => {
tryToEnableYesterdaySync();
}, []);
const tryToEnableYesterdaySync = async () => {
console.log("Attempting to enable yesterday sync...");
try {
const userAcceptedYesterdaySync = await AsyncStorage.getItem(
"ACCEPTED_YESTERDAY_SYNC"
);
const accepted = userAcceptedYesterdaySync === "true";
if (accepted) {
console.log("User accepted yesterday sync");
await scheduleYesterdaySync("oldest");
} else {
console.log("User did not accept yesterday sync");
}
} catch (error) {
console.error("Error retrieving data from AsyncStorage:", error);
}
};
return <View>{/* Your UI components here */}</View>;
}
export default MyComponent;
RookYesterdaySyncPermissions
scheduleYesterdaySync
Requires 2 types of permissions
- Android
- POST_NOTIFICATIONS
- FOREGROUND_SERVICE
- FOREGROUND_SERVICE_HEALTH
- ACTIVITY_RECOGNITION
- Health Connect
- SLEEP
- PHYSICAL
- BODY
To request or check both types of permissions use the you have to request permissions of health connect with useRookSyncPermissions().requestPermissions()
in order to access to the health connect data and useRookSyncPermissions().requestAndroidBackgroundPermissions()
to have access to the background services
Customizing the foreground service notification
To sync health data automatically a Foreground Service is used, this service requires a notification to be displayed until the synchronization finishes.
To use your own resources you need to reference them in the AndroidManifest.xml file:
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<application>
<meta-data
android:name="io.tryrook.service.notification.SYNC_ICON"
android:resource="@drawable/my_custom_icon"/>
<meta-data
android:name="io.tryrook.service.notification.SYNC_TITLE"
android:resource="@string/my_custom_title"/>
<meta-data
android:name="io.tryrook.service.notification.SYNC_CONTENT"
android:resource="@string/my_custom_content"/>
</application>
</manifest>
Starting on Android 13 (SDK 33) this notification can be dismissed without finishing the service associated with it, then the service will be displayed in the active apps section (This may vary depending on device brand).
Launch/Stop conditions
scheduleYesterdaySync
won't start or will stop if one the following conditions are meet:
- The device battery is low
- The device storage is low
- The device is not connected to the internet
- The user hasn't granted Android Permissions (POST_NOTIFICATIONS, FOREGROUND_SERVICE, FOREGROUND_SERVICE_HEALTH)
- The device has previously exceeded the Health Connect request quota and the recovery timestamp hasn't been meet
- The user hasn't granted Health Connect Permissions (SLEEP, PHYSICAL, BODY)
- The most recent request exceeded the Health Connect request quota
- The userID hasn't been configured
- There is an error initializing the SDK
Additional information
Health Connect request quota
To maintain optimal system stability and performance, Health Connect imposes rate limits on client connections to the Health Connect API.
It is important for you to understand that every data type in rook-sdk is constructed of multiple health variables like heart rate, steps count, hydration, etc. So when a Sleep Summary is extracted there are multiple calls made to the Health Connect API, and whereas in the last months our efforts have been focused on optimizing and reducing the number of API call required for each data type it's still possible for that limit to be reached, especially while doing multiple extraction in a short amount of time.
Depending on the sync type you chose you must have the following things in mind:
Request quota when syncing data manually
- Extract summaries once daily: Since summaries collect health data from a previous day, there's no need to extract them more than once per day.
- Use what you already have: If you are extracting Physical Events you don’t need to extract Heart Rate Events ( Physical) or Oxygenation Events (Physical) as these are already included in the PhysicalEvent object.
- Only sync the relevant health data for you use case: If you are not interested on individual events and only want to
sync the summary of a specific date, just use the
sync
functions inuseRookSyncSummaries
. - If you already reached the request quota avoid calling any
sync
function for the next hours so your quota can be recovered.
Request quota when syncing data automatically
scheduleYesterdaySync
already takes care of practically all issues and limitations of Health Connect. When the
quota is reached, all pending syncs are canceled, and a recovery timestamp is created. Pending syncs will not resume
until the user re-opens the app after a few hours.
Auto start
After a call to enableBackgroundAndroidSteps
if the device is restarted the Foreground service will start after the
user unlocks their device for the first time (This may vary depending on device brand). This behaviour will be stopped
when calling disableBackgroundAndroidSteps
.
Considerations
The steps service is designed to always be active but there are certain scenarios where the service could not behave as intended:
- If the user force closes the application from settings, and then restarts their device the service may not be able to restart.
- The steps are scheduled to be uploaded every hour from the time
enableBackgroundAndroidSteps
was called, however it's not possible to guarantee the exact execution time as this depends on how the Android System manages the device resources.
Listen for Permissions Notifications
The ROOK SDK allows you to listen for permission notifications, enabling you to respond to changes in permissions, as shown in the following example:
import { getRookModule } from "react-native-rook-sdk";
...
useEffect(() => {
const rookModule = getRookModule();
const eventEmitter = new NativeEventEmitter(rookModule);
// Subscribe to the event
const subscription = eventEmitter.addListener(
"ROOK_NOTIFICATION",
handleRookNotification
);
// Clean up subscription when the component unmounts
return () => {
subscription.remove();
};
}, []);
const handleRookNotification = (notification) => {
const { type, value, message } = notification;
switch (type) {
case "ROOK_BACKGROUND_ANDROID_PERMISSIONS":
console.log(`Background permissions on Android: ${value}`);
break;
case "ROOK_HEALTH_CONNECT_PERMISSIONS":
console.log(`Health Connect permissions: ${value}`);
break;
case "ROOK_BACKGROUND_ENABLED":
console.log(`Background services enabled: ${value}`);
break;
default:
console.log(`Unknown notification: ${message}`);
}
};
The notification type indicates the following:
ROOK_BACKGROUND_ANDROID_PERMISSIONS
: Specifies whether the user has granted Android permissions.ROOK_HEALTH_CONNECT_PERMISSIONS
: Specifies whether the user has granted Health Connect permissions.ROOK_BACKGROUND_ENABLED
: Indicates whether background sync was successfully enabled."