Skip to main content

Rook SDK

This SDK enables apps to extract and upload data from Apple Health and Health Connect. With this SDK, you will be able to extract and upload data. For more information, check out our demo app.

Installation

info

To build a project using ROOK in React Native, you need to use at least React v18 and React Native v70.

  • The minimum version of Android SDK is 26, the target SDK is 34, and the Kotlin version is >= 1.8.10.**
  • The SDK requires Xcode 14.0.1 or higher. To run your app using the ROOK SDK on a connected device with iOS 16.2 or later, you need Xcode 14.2 or higher.
  • The minimum version of iOS is 13.0.

npm

npm i react-native-rook-sdk

yarn

yarn add react-native-rook-sdk

Configuration

Add your client uuid in order to be authorized, follow the next example, add at the top level of your tree components the RookSyncGate, password refers to the secret key.

import { RookSyncGate } from "react-native-rook-sdk";

<RookSyncGate
environment="sandbox | production"
clientUUID="YOUR_CLIENT_UUID"
password="YOUR_PASSWORD"
enableLogs={true | false | undefined}
enableBackgroundSync={true | false}
enableEventsBackgroundSync={true | false | undefined}
>
<YOUR_COMPONENTS />
</RookSyncGate>;

The value of enableLogs will display or not local logs in the console for certain SDK operations. We recommend you to ask your users if they want to enable the automatic sync, then save their preference in local storage and set enableBackgroundSync conditionally.

The value of enableEventsBackgroundSync will include or exclude the events of the background sync.

iOS Configuration

Then we need to add Apple Health Kit Framework to our project in order to that please:

  • Open your project in Xcode.
  • Click on your project file in the Project Navigator.
  • Select your target and then click on the "Build Phases" tab.
  • Click on the "+" button under the "Link Binary With Libraries" section and select "HealthKit.framework" from the list.
  • Select your target and then click on the "Signing Capabilities" tab.
  • Click on "Add Capability" and search for "HealthKit"

Additionally add the following to the info.plist

<key>NSHealthShareUsageDescription</key>
<string>This app requires access to your health and fitness data in order to track your workouts and activity levels.</string>
<key>NSHealthUpdateUsageDescription</key>
<string>This app requires permission to write healt data to HealthKit.</string>

Android Configuration

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 for Android

info

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 for Android

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 for Android

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

useRookConfiguration

This hook will help you to configure the user ID you want to sync.

const useRookConfiguration = () => {
ready: boolean;
getUserID: () => Promise<string>;
updateUserID: (userID: string) => Promise<boolean>;
clearUserID: () => Promise<boolean>;
syncUserTimeZone: () => Promise<boolean>;
removeUserFromRook: () => Promise<boolean>;
enableAppleHealthSync: () => Promise<boolean>;
disableAppleHealthSync: () => Promise<boolean>;
isAppleHealthSyncEnabled: () => Promise<boolean>;
scheduleAndroidYesterdaySync: (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.

  • removeUserFromRook: Remove the user from the Rook services.

  • enableAppleHealthSync: This function enables the automatic upload of the summaries from the previous day of the current device's date. Every time the user opens the app it will try to upload the summaries, before use this function is necessary to add a user id and request permissions.

  • disableAppleHealthSync: This function disables the automatic upload of the summaries from the previous day of the current device's date.

  • isAppleHealthSyncEnabled: This function checks if the Apple Health Sync is enabled.

  • scheduleAndroidYesterdaySync: The function scheduleAndroidYesterdaySync 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.

info

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.

useRookPermissions

This hook will help you to request permissions to extract data.

const useRookPermissions: () => {
ready: boolean;
checkAvailability: () => Promise<boolean>;
hasAndroidBackgroundPermissions: () => Promise<boolean>;
healthConnectHasPermissions: () => Promise<boolean>;
openHealthConnectSettings: () => Promise<void>;
requestAllAppleHealthPermissions: () => Promise<void>;
requestAllHealthConnectPermissions: () => Promise<void>;
requestAllPermissions: () => Promise<RequestStatusPermissions>;
requestAndroidBackgroundPermissions: () => Promise<RequestStatusPermissions>;
shouldRequestAndroidBackgroundPermissions: () => Promise<boolean>;
};
  • ready: Indicates when the hook is ready to work.
  • hasAndroidBackgroundPermissions: Check if the sdk have the permissions to start services in background.
  • healthConnectHasPermissions: check if we have permissions for health connect this function only works for android.
  • openHealthConnectSettings: Open Health Connect settings.
  • requestAllAppleHealthPermissions: Request all the permissions for apple health
  • requestAllHealthConnectPermissions: Request all the permissions for health connect.
  • requestAllPermissions: Request the permissions for health connect, return two possible values REQUEST_SENT means that the view requesting permissions was shown or ALREADY_GRANTED means that the user is allowed to request permissions, in iOS will always return REQUEST_SENT because Apple Health do not notify if the user allows permissions or not.
  • requestAndroidBackgroundPermissions: Request the permissions for enable background sync for android, return two possible values REQUEST_SENT means that the alerts requesting permissions was shown or ALREADY_GRANTED means that the user is allowed to request permissions.
  • shouldRequestAndroidBackgroundPermissions: Check if is necessary to request background permissions
info

Each method will return a promise if the permission window was successfully presented. This value does not indicate whether the user actually granted permission. Please keep in mind that Apple Health does not allow checking the status of permissions for types requested to be read. If the user does not allow data type reading, either by mistake or on purpose, it will simply appear as if there is no data of the requested type in the HealthKit store. Any further changes must be performed by the user through the Apple Health application.

useRookSummaries

This hook will help you to extract and send data from apple health to Rook servers.

const useRookSummaries: () => {
ready: boolean;
shouldSyncFor: (date: string) => Promise<boolean>;
syncSleepSummary: (date: string) => Promise<void>;
syncPhysicalSummary: (date: string) => Promise<void>;
syncBodySummary: (date: string) => Promise<void>;
reSyncFailedSummaries: () => Promise<void>;
};
  • ready: Indicates when the hook is ready to work.
  • shouldSyncFor: Checks if that specific date are data available.
  • syncSleepSummary: Send the summary to rook servers.
  • syncBodySummary: Send the summary to rook servers.
  • syncPhysicalSummary: Send the summary to rook servers.
  • reSyncFailedSummaries: In case you try to sync a summary and fail, this function help to try to send again.

useRookEvents

This hook will help you to extract and send data from apple health to Rook servers.

const useRookEvents: () => {
ready: boolean;
syncBodyHeartRateEvent: (date: string) => Promise<void>;
syncPhysicalHeartRateEvent: (date: string) => Promise<void>;
syncBodyOxygenationEvent: (date: string) => Promise<void>;
syncPhysicalOxygenationEvent: (date: string) => Promise<void>;
syncTrainingEvent: (date: string) => Promise<void>;
syncTemperatureEvent: (date: string) => Promise<void>;
syncBloodPressureEvent: (date: string) => Promise<void>;
syncBloodGlucoseEvent: (date: string) => Promise<void>;
syncBodyMetricsEvent: (date: string) => Promise<void>;
syncHealthConnectHydrationEvents: (date: string) => Promise<void>;
syncHealthConnectNutritionEvents: (date: string) => Promise<void>;
reSyncFailedEvents: () => Promise<void>;
};
  • ready: Indicates when the hook is ready to work.
  • syncBodyHeartRateEvents: Send body heart rate events for the specified date.
  • syncPhysicalHeartRateEvents: Send physical heart rate events for the specified date.
  • syncBodyOxygenationEvents: Send body oxygenation events for the specified date.
  • syncPhysicalOxygenationEvents: Send physical oxygenation events for the specified date.
  • syncTrainingEvent: Send training events for the specified date.
  • syncTemperatureEvent: Send temperature events for the specified date.
  • syncBloodPressureEvent: Send pressure events for the specified date.
  • syncBloodGlucoseEvent: Send glucose events for the specified date.
  • syncHealthConnectHydrationEvents: Send hydration events for the specified date.
  • syncHealthConnectNutritionEvents: Send nutrition events for the specified date.
  • syncBodyMetricsEvent: Send body metrics events for the specified date, like change of weight or height.

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.

export interface DataSource {
name: string;
authorizationURL: string;
imageUrl: string;
description: string;
connected: boolean;
}

export type DataSourceType =
| "Garmin"
| "Oura"
| "Polar"
| "Fitbit"
| "Withings"
| "Whoop";

type options = {
redirectURL?: string;
};

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 param
  • presentDataSourceView: Present a default view with the available data sources, with the ability to configure with the options param
  • revokeDataSource: Revokes user authorization for the specified data source.

useRookAndroidBackgroundSteps

This hook will help you to extract and send data from health connect to Rook servers.

const useRookAndroidBackgroundSteps: () => {
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. This function is deprecated and it will be removed in next versions, please use instead useRookSyncPermissions().requestAndroidBackgroundPermissions() - Request permissions to get the steps.
  • enableBackgroundAndroidSteps: Start the service for get the steps, and collect all the steps for 12hrs 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:

  1. Request Permissions
  2. Enable background Android steps
  3. 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>
info

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).

Additional information

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.

useRookAppleHealthVariables

This hook will help you to extract and send data from apple health to Rook servers.

const useRookAppleHealthVariables: () => {
ready: boolean;
getTodaySteps: () => Promise<void>;
};
  • ready: Indicates when the hook is ready to work.
  • getTodaySteps: Gets the steps accumulated for the current day.

Additional

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 in useRookSyncSummaries.
  • 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.

Continuous Upload for iOS

The hook useRookConfiguration helps you to enable or disable continuous data upload. every time a user opens the app, the sdk will try to upload the data from the previous day of the device's current date.

Note: before enable this feature it is necessary to add a user a request permission from apple health

MethodDescription
enableAppleHealthSyncThis method enables the automatic upload of the summaries from the previous day of the current device's date. Every time the user opens the app it will try to upload the summaries, before use this method is necessary to add a user id and request permissions.
disableAppleHealthSyncThis method disables the automatic upload of the summaries from the previous day of the current device's date.

Background Upload for iOS

useRookAppleHealth

The hook useRookAppleHealth helps to enable background upload for summaries, this allows to your app to upload health data while your app is in background. it is recommended to combine continuous upload, background upload and manual sync for a better performance.

const useRookAppleHealth = () => {
ready: boolean;
enableBackGroundUpdates: () => Promise<void>;
disableBackGroundUpdates: () => Promise<void>;
isBackGroundForSummariesEnable: () => Promise<boolean>;
isBackGroundForEventsEnable: () => Promise<boolean>;
}
  • ready: Indicates when the hook is ready to work.
  • enableBackGroundUpdates : Enables the background updates
  • disableBackGroundUpdates: Disables the background updates
  • isBackGroundForSummariesEnable: Checks if the summaries are syncing in the background
  • isBackGroundForEventsEnable: Checks if the events are syncing in the background
info

For security, iOS devices encrypt the HealthKit storage when users lock their devices. As a result, apps may not be able to read data from Apple Health when it runs in the background. Please refer to the official documentation for more information.

MethodDescription
disableBackGroundUpdatesThis method enables the background upload of the summaries.
disableBackGroundUpdatesThis method disables the background upload of the summaries.

To configure background upload you need to follow the steps bellow:

  • Add health kit to your project and enable background delivery.
  • Add Background modes and enable Background fetch.

background_delivery

  • In the app delegate of your app add the setBackListeners method in didFinishLaunchingWithOptions function.

Example


#import "AppDelegate.h"
#import "RookSDK/RookSDK-Swift.h"
#import <React/RCTBundleURLProvider.h>

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.moduleName = @"RookSdkAppleHealthExample";
// You can add your custom initial props in the dictionary below.
// They will be passed down to the ViewController used by React Native.
self.initialProps = @{};
[[RookBackGroundSync shared] setBackListeners];

return [super application:application didFinishLaunchingWithOptions:launchOptions];
}

- (NSURL *)sourceURLForBridge:(RCTBridge *)bridge
{
#if DEBUG
return [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index"];
#else
return [[NSBundle mainBundle] URLForResource:@"main" withExtension:@"jsbundle"];
#endif
}

@end

Background Upload for Android

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 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, you need to request permissions for Health Connect with useRookSyncPermissions().requestPermissions() to access Health Connect data and useRookSyncPermissions().requestAndroidBackgroundPermissions() to access 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>
info

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