### Install React Native Health Connect Source: https://matinzd.github.io/react-native-health-connect/docs/get-started Use npm to install the react-native-health-connect package. This is the primary step to include the library in your project. ```bash npm install react-native-health-connect ``` -------------------------------- ### React Native Health Connect Initialization and Data Reading Example Source: https://matinzd.github.io/react-native-health-connect/docs/get-started A JavaScript example demonstrating how to initialize the react-native-health-connect client, request read permissions for 'ActiveCaloriesBurned', and then read the corresponding records within a specified time range. ```javascript import { initialize, requestPermission, readRecords, } from 'react-native-health-connect'; const readSampleData = async () => { // initialize the client const isInitialized = await initialize(); // request permissions const grantedPermissions = await requestPermission([ { accessType: 'read', recordType: 'ActiveCaloriesBurned' }, ]); // check if granted const { records } = await readRecords('ActiveCaloriesBurned', { timeRangeFilter: { operator: 'between', startTime: '2023-01-09T12:00:00.405Z', endTime: '2023-01-09T23:53:15.405Z', }, }); }; ``` -------------------------------- ### Install Expo Health Connect and Build Properties Source: https://matinzd.github.io/react-native-health-connect/docs/get-started Installs the necessary expo-health-connect and expo-build-properties packages using npm. These are essential for integrating health connect features into your Expo application. ```bash npm install expo-health-connect npm install expo-build-properties --save-dev ``` -------------------------------- ### Setup MainActivity for Kotlin Projects Source: https://matinzd.github.io/react-native-health-connect/docs/get-started For Kotlin-based React Native projects using version 2 or later, modify the MainActivity.kt file. This involves importing necessary classes and setting the HealthConnectPermissionDelegate within the onCreate method to handle permission results. ```kotlin package com.healthconnectexample import android.os.Bundle import com.facebook.react.ReactActivity import com.facebook.react.ReactActivityDelegate import com.facebook.react.defaults.DefaultNewArchitectureEntryPoint.fabricEnabled import com.facebook.react.defaults.DefaultReactActivityDelegate import dev.matinzd.healthconnect.permissions.HealthConnectPermissionDelegate class MainActivity : ReactActivity() { /** * Returns the name of the main component registered from JavaScript. This is used to schedule * rendering of the component. */ override fun getMainComponentName(): String = "HealthConnectExample" override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) // In order to handle permission contract results, we need to set the permission delegate. HealthConnectPermissionDelegate.setPermissionDelegate(this) } /** * Returns the instance of the [ReactActivityDelegate]. We use [DefaultReactActivityDelegate] * which allows you to enable New Architecture with a single boolean flags [fabricEnabled] */ override fun createReactActivityDelegate(): ReactActivityDelegate = DefaultReactActivityDelegate(this, mainComponentName, fabricEnabled) } ``` -------------------------------- ### Setup MainActivity for Java Projects Source: https://matinzd.github.io/react-native-health-connect/docs/get-started For Java-based React Native projects using version 2 or later, modify the MainActivity.java file. This requires importing specific classes and initializing the HealthConnectPermissionDelegate with an application ID in the onCreate method. ```java package com.healthconnectexample import android.os.Bundle import com.facebook.react.ReactActivity import com.facebook.react.ReactActivityDelegate import com.facebook.react.defaults.DefaultNewArchitectureEntryPoint.fabricEnabled import com.facebook.react.defaults.DefaultReactActivityDelegate import dev.matinzd.healthconnect.permissions.HealthConnectPermissionDelegate class MainActivity : ReactActivity() { /** * Returns the name of the main component registered from JavaScript. This is used to schedule * rendering of the component. */ override fun getMainComponentName(): String = "HealthConnectExample" override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) // In order to handle permission contract results, we need to set the permission delegate. HealthConnectPermissionDelegate.INSTANCE.setPermissionDelegate(this, "com.google.android.apps.healthdata"); } /** * Returns the instance of the [ReactActivityDelegate]. We use [DefaultReactActivityDelegate] * which allows you to enable New Architecture with a single boolean flags [fabricEnabled] */ override fun createReactActivityDelegate(): ReactActivityDelegate = DefaultReactActivityDelegate(this, mainComponentName, fabricEnabled) } ``` -------------------------------- ### Configure Expo App.json for Health Connect Source: https://matinzd.github.io/react-native-health-connect/docs/get-started Configures the app.json file to include the expo-health-connect plugin. This step is crucial for Expo to recognize and apply the health connect functionalities. ```json { "expo": { "plugins": ["expo-health-connect"] } } ``` -------------------------------- ### Retrieve Single Record Example - JavaScript Source: https://matinzd.github.io/react-native-health-connect/docs/api/methods/readRecord This JavaScript example demonstrates how to use the `readRecord` function to fetch a single 'ActiveCaloriesBurned' record. It imports the function, calls it with a sample record type and ID, and logs the retrieved record to the console upon successful retrieval. Error handling for the promise is recommended in production code. ```javascript import { readRecord } from 'react-native-health-connect'; const readSampleDataSingle = () => { readRecord( 'ActiveCaloriesBurned', 'a7bdea65-86ce-4eb2-a9ef-a87e6a7d9df2' ).then((result) => { console.log('Retrieved record: ', JSON.stringify({ result }, null, 2)); }); }; ``` -------------------------------- ### Configure Expo Build Properties in App.json Source: https://matinzd.github.io/react-native-health-connect/docs/get-started Adds build properties to the app.json, specifically configuring Android's compileSdkVersion, targetSdkVersion, and minSdkVersion. This ensures compatibility and proper build settings for Android. ```json { "expo": { "plugins": [ [ "expo-build-properties", { "android": { "compileSdkVersion": 34, "targetSdkVersion": 34, "minSdkVersion": 26 } } ] ] } } ``` -------------------------------- ### Get Granted Permissions Source: https://matinzd.github.io/react-native-health-connect/docs/api/methods/getGrantedPermissions Retrieves a set of all health permissions that have been granted by the user to the calling application. ```APIDOC ## getGrantedPermissions ### Description Returns a set of all health permissions granted by the user to the calling provider app. ### Method ```javascript getGrantedPermissions() ``` ### Endpoint N/A (This is a client-side function call) ### Parameters None ### Request Example ```javascript import { getGrantedPermissions } from 'react-native-health-connect'; const readGrantedPermissions = () => { getGrantedPermissions().then((permissions) => { console.log('Granted permissions ', { permissions }); }); }; ``` ### Response #### Success Response (Promise) - **permissions** (Array) - An array of granted health permissions. #### Response Example ```json { "permissions": [ { "accessLevel": "read", "permission": "Steps" }, { "accessLevel": "write", "permission": "HeartRate" } ] } ``` ``` -------------------------------- ### Request Exercise Route Write Permission Source: https://matinzd.github.io/react-native-health-connect/docs/permissions This code snippet demonstrates how to request the special permission required to write exercise routes using the React Native Health Connect library. It specifies the 'write' access type and 'ExerciseRoute' record type. Ensure all necessary dependencies for health connect are installed and configured. ```javascript requestPermission([ { accessType: 'write', recordType: 'ExerciseRoute', } // Other permissions... ]); ``` -------------------------------- ### Insert Records into Health Connect using JavaScript Source: https://matinzd.github.io/react-native-health-connect/docs/api/methods/insertRecords This snippet demonstrates how to use the `insertRecords` function from the 'react-native-health-connect' library to insert multiple 'ActiveCaloriesBurned' records. It takes an array of HealthConnectRecord objects, each with details like record type, energy, start and end times, and optional metadata. The function returns a Promise that resolves with an array of UUIDs for the inserted records. If any insertion fails, the entire transaction is rolled back. ```javascript import { insertRecords } from 'react-native-health-connect'; const insertSampleData = () => { insertRecords([ { recordType: 'ActiveCaloriesBurned', energy: { unit: 'kilocalories', value: 10000 }, startTime: '2023-01-09T10:00:00.405Z', endTime: '2023-01-09T11:53:15.405Z', metadata: { recordingMethod: RecordingMethod.RECORDING_METHOD_AUTOMATICALLY_RECORDED, device: { manufacturer: 'Google', model: 'Pixel 4', type: DeviceType.TYPE_PHONE, }, }, }, { recordType: 'ActiveCaloriesBurned', energy: { unit: 'kilocalories', value: 15000 }, startTime: '2023-01-09T12:00:00.405Z', endTime: '2023-01-09T23:53:15.405Z', }, ]).then((ids) => { console.log('Records inserted ', { ids }); // Records inserted {"ids": ["06bef46e-9383-4cc1-94b6-07a5045b764a", "a7bdea65-86ce-4eb2-a9ef-a87e6a7d9df2"]} }); }; ``` -------------------------------- ### Get Granted Health Permissions (JavaScript) Source: https://matinzd.github.io/react-native-health-connect/docs/api/methods/getGrantedPermissions Retrieves a set of all health permissions granted by the user to the calling provider app. This function returns a Promise that resolves to an array of `Permission` objects. Ensure the `react-native-health-connect` library is installed and imported. ```javascript import { getGrantedPermissions } from 'react-native-health-connect'; const readGrantedPermissions = () => { getGrantedPermissions().then((permissions) => { console.log('Granted permissions ', { permissions }); }); }; ``` -------------------------------- ### SDK Status and Initialization Source: https://matinzd.github.io/react-native-health-connect/docs/api/overview Methods to determine the availability of the Health Connect SDK and initialize the client. ```APIDOC ## GET /sdkStatus ### Description Determines whether an implementation of HealthConnectClient is available on the device at the moment. If none is available, apps may choose to redirect to package installers to find suitable providers. ### Method GET ### Endpoint /sdkStatus ### Parameters #### Query Parameters None ### Request Example None ### Response #### Success Response (200) - **status** (string) - Indicates if the SDK is available ('available' or 'unavailable'). #### Response Example ```json { "status": "available" } ``` ## POST /initialize ### Description Initialize the health connect client. ### Method POST ### Endpoint /initialize ### Parameters #### Query Parameters None ### Request Example None ### Response #### Success Response (200) - **initialized** (boolean) - True if the client was initialized successfully, false otherwise. #### Response Example ```json { "initialized": true } ``` ``` -------------------------------- ### Exercise Route Source: https://matinzd.github.io/react-native-health-connect/docs/api/overview Method to request permission for accessing exercise route data. ```APIDOC ## POST /requestExerciseRoute ### Description Requests permission to access exercise route data for a specific exercise session. ### Method POST ### Endpoint /requestExerciseRoute ### Parameters #### Request Body - **exerciseSessionId** (string) - Required - The unique identifier for the exercise session. ### Request Example ```json { "exerciseSessionId": "session-abc-123" } ``` ### Response #### Success Response (200) - **granted** (boolean) - True if the permission was granted, false otherwise. #### Response Example ```json { "granted": true } ``` ``` -------------------------------- ### Record Management (Insert, Read, Aggregate, Delete) Source: https://matinzd.github.io/react-native-health-connect/docs/api/overview Methods for inserting, reading, aggregating, and deleting health records. ```APIDOC ## POST /insertRecords ### Description Inserts one or more records and returns newly assigned generated UUIDs. Insertion of multiple records is executed in a transaction - if one fails, none is inserted. ### Method POST ### Endpoint /insertRecords ### Parameters #### Request Body - **records** (array) - Required - An array of record objects to insert. - Each record object should have a 'recordType' and other type-specific fields. ### Request Example ```json { "records": [ { "recordType": "Steps", "count": 1000, "startTime": "2023-10-27T10:00:00Z", "endTime": "2023-10-27T10:05:00Z" } ] } ``` ### Response #### Success Response (200) - **uuids** (array) - An array of UUIDs for the newly inserted records. #### Response Example ```json { "uuids": ["uuid-1234-abcd"] } ``` ## POST /readRecords ### Description Retrieves a collection of records. ### Method POST ### Endpoint /readRecords ### Parameters #### Request Body - **recordType** (string) - Required - The type of health record to read. - **timeRangeFilter** (object) - Optional - Filters records within a specified time range. - **startTime** (string) - Required if timeRangeFilter is present - The start time in ISO 8601 format. - **endTime** (string) - Required if timeRangeFilter is present - The end time in ISO 8601 format. - **dataOriginFilter** (array) - Optional - Filters records by data origin package names. ### Request Example ```json { "recordType": "Steps", "timeRangeFilter": { "startTime": "2023-10-26T00:00:00Z", "endTime": "2023-10-27T00:00:00Z" } } ``` ### Response #### Success Response (200) - **records** (array) - An array of matching record objects. #### Response Example ```json { "records": [ { "recordType": "Steps", "count": 1500, "startTime": "2023-10-26T10:00:00Z", "endTime": "2023-10-26T10:05:00Z", "uuid": "uuid-5678-efgh", "dataOrigin": {"packageName": "com.example.app"} } ] } ``` ## POST /readRecord ### Description Retrieves a single record of the specified type. ### Method POST ### Endpoint /readRecord ### Parameters #### Request Body - **recordType** (string) - Required - The type of health record to read. - **uuid** (string) - Required - The UUID of the specific record to retrieve. ### Request Example ```json { "recordType": "HeartRate", "uuid": "uuid-1122-3344" } ``` ### Response #### Success Response (200) - **record** (object) - The requested record object. #### Response Example ```json { "record": { "recordType": "HeartRate", "beatsPerMinute": 75, "time": "2023-10-27T11:00:00Z", "uuid": "uuid-1122-3344", "dataOrigin": {"packageName": "com.example.app"} } } ``` ## POST /aggregateRecord ### Description Reads aggregated results according to requested read criteria, for example, data origin filter and within a time range. ### Method POST ### Endpoint /aggregateRecord ### Parameters #### Request Body - **recordType** (string) - Required - The type of health record to aggregate. - **timeRangeFilter** (object) - Required - Filters records within a specified time range. - **startTime** (string) - Required - The start time in ISO 8601 format. - **endTime** (string) - Required - The end time in ISO 8601 format. - **aggregationType** (string) - Required - The type of aggregation (e.g., 'sum', 'average', 'count'). - **dataOriginFilter** (array) - Optional - Filters records by data origin package names. ### Request Example ```json { "recordType": "Steps", "timeRangeFilter": { "startTime": "2023-10-26T00:00:00Z", "endTime": "2023-10-27T00:00:00Z" }, "aggregationType": "sum" } ``` ### Response #### Success Response (200) - **aggregatedResult** (object) - The aggregated result. - **result** (number) - The aggregated value. #### Response Example ```json { "aggregatedResult": { "result": 15000 } } ``` ## DELETE /deleteRecordsByUuids ### Description Deletes one or more records by their identifiers. Deletion of multiple records is executed in a single transaction - if one fails, none is deleted. ### Method DELETE ### Endpoint /deleteRecordsByUuids ### Parameters #### Request Body - **recordType** (string) - Required - The type of health record to delete. - **uuids** (array) - Required - An array of UUIDs of the records to delete. ### Request Example ```json { "recordType": "Weight", "uuids": ["uuid-abcd-1234", "uuid-efgh-5678"] } ``` ### Response #### Success Response (200) - **deleted** (boolean) - True if the records were deleted successfully, false otherwise. #### Response Example ```json { "deleted": true } ``` ## DELETE /deleteRecordsByTimeRange ### Description Deletes any record of the given record type in the given time range (automatically filtered to a record belonging to the calling application). Deletion of multiple records is executed in a transaction - if one fails, none is deleted. ### Method DELETE ### Endpoint /deleteRecordsByTimeRange ### Parameters #### Request Body - **recordType** (string) - Required - The type of health record to delete. - **timeRangeFilter** (object) - Required - Filters records within a specified time range. - **startTime** (string) - Required - The start time in ISO 8601 format. - **endTime** (string) - Required - The end time in ISO 8601 format. ### Request Example ```json { "recordType": "Sleep", "timeRangeFilter": { "startTime": "2023-10-25T00:00:00Z", "endTime": "2023-10-26T00:00:00Z" } } ``` ### Response #### Success Response (200) - **deleted** (boolean) - True if the records were deleted successfully, false otherwise. #### Response Example ```json { "deleted": true } ``` ``` -------------------------------- ### Health Connect App Interaction Source: https://matinzd.github.io/react-native-health-connect/docs/api/overview Methods to open Health Connect settings and data management screens. ```APIDOC ## POST /openHealthConnectSettings ### Description Opens Health Connect app's settings app. ### Method POST ### Endpoint /openHealthConnectSettings ### Parameters None ### Request Example None ### Response #### Success Response (200) - **opened** (boolean) - True if the settings screen was opened successfully, false otherwise. #### Response Example ```json { "opened": true } ``` ## POST /openHealthConnectDataManagement ### Description Opens Health Connect data management screen app. ### Method POST ### Endpoint /openHealthConnectDataManagement ### Parameters None ### Request Example None ### Response #### Success Response (200) - **opened** (boolean) - True if the data management screen was opened successfully, false otherwise. #### Response Example ```json { "opened": true } ``` ``` -------------------------------- ### Initialize Health Connect Client Source: https://matinzd.github.io/react-native-health-connect/docs/api/methods/initialize Initializes the health connect client. You can optionally specify the provider package name. If not provided, it defaults to `com.google.android.apps.healthdata`. ```APIDOC ## POST /initialize ### Description Initializes the health connect client with specific providers. If `providerPackageName` is not provided, the default Health Connect application package name will be considered `com.google.android.apps.healthdata`. ### Method POST ### Endpoint /initialize ### Parameters #### Query Parameters - **providerPackageName** (string) - Optional - The package name of the Health Connect provider. ### Request Example ```json { "providerPackageName": "com.example.healthapp" } ``` ### Response #### Success Response (200) - **initialized** (boolean) - Indicates whether the client was successfully initialized. #### Response Example ```json { "initialized": true } ``` ### Example Usage ```javascript import { initialize } from 'react-native-health-connect'; const initializeHealthConnect = async () => { try { const isInitialized = await initialize('com.google.android.apps.healthdata'); console.log('Health Connect initialized:', isInitialized); } catch (error) { console.error('Error initializing Health Connect:', error); } }; initializeHealthConnect(); ``` ``` -------------------------------- ### Initialize Health Connect Client (JavaScript) Source: https://matinzd.github.io/react-native-health-connect/docs/api/methods/initialize Initializes the Health Connect client for React Native. If `providerPackageName` is not specified, it defaults to 'com.google.android.healthconnect'. This function returns a Promise that resolves to a boolean indicating success. ```javascript import { initialize } from 'react-native-health-connect'; const initializeHealthConnect = async () => { const isInitialized = await initialize(); console.log({ isInitialized }); }; ``` -------------------------------- ### Create PermissionRationaleActivity for Health Connect (React Native CLI) Source: https://matinzd.github.io/react-native-health-connect/docs/permissions This Kotlin code defines an Activity that displays a WebView to show the rationale for Health Connect permissions. This activity is launched when the user needs to understand why certain health data permissions are required, typically linked via an intent filter. ```kotlin package com.healthconnectexample import android.os.Bundle import android.webkit.WebResourceRequest import android.webkit.WebView import android.webkit.WebViewClient import androidx.appcompat.app.AppCompatActivity class PermissionsRationaleActivity: AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val webView = WebView(this) webView.webViewClient = object : WebViewClient() { override fun shouldOverrideUrlLoading(view: WebView?, request: WebResourceRequest?): Boolean { return false } } webView.loadUrl("https://developer.android.com/health-and-fitness/guides/health-connect/develop/get-started") setContentView(webView) } } ``` -------------------------------- ### Configure Activity and Alias for Health Connect Permissions Rationale (React Native CLI) Source: https://matinzd.github.io/react-native-health-connect/docs/permissions This XML snippet configures the AndroidManifest.xml to include activities and an activity-alias for handling the display of Health Connect permission rationales. It ensures that the correct activity is launched based on the Android version and the action requested by the system. ```xml + + + + + + + + + + + + + + + + + ``` -------------------------------- ### Permission Management Source: https://matinzd.github.io/react-native-health-connect/docs/api/overview Methods for requesting, retrieving, and revoking user permissions for Health Connect data. ```APIDOC ## POST /requestPermission ### Description Request permission for specified record types and access types. ### Method POST ### Endpoint /requestPermission ### Parameters #### Request Body - **recordType** (string) - Required - The type of health record to request permission for (e.g., 'Steps', 'HeartRate'). - **accessType** (string) - Required - The type of access requested ('read' or 'write'). ### Request Example ```json { "recordType": "Steps", "accessType": "read" } ``` ### Response #### Success Response (200) - **granted** (boolean) - True if the permission was granted, false otherwise. #### Response Example ```json { "granted": true } ``` ## GET /getGrantedPermissions ### Description Returns a set of all health permissions granted by the user to the calling provider app. ### Method GET ### Endpoint /getGrantedPermissions ### Parameters None ### Request Example None ### Response #### Success Response (200) - **permissions** (array) - A list of granted permission objects, each with 'recordType' and 'accessType'. #### Response Example ```json { "permissions": [ {"recordType": "Steps", "accessType": "read"}, {"recordType": "HeartRate", "accessType": "write"} ] } ``` ## POST /revokeAllPermissions ### Description Revokes all previously granted permissions by the user to the calling app. ### Method POST ### Endpoint /revokeAllPermissions ### Parameters None ### Request Example None ### Response #### Success Response (200) - **revoked** (boolean) - True if all permissions were revoked successfully, false otherwise. #### Response Example ```json { "revoked": true } ``` ``` -------------------------------- ### Check Health Connect SDK Availability (JavaScript) Source: https://matinzd.github.io/react-native-health-connect/docs/api/methods/getSdkStatus This JavaScript snippet demonstrates how to use the `getSdkStatus` function from the 'react-native-health-connect' library to determine the availability of the Health Connect SDK. It handles different availability statuses, including SDK available, unavailable, and unavailable with a provider update required. No external dependencies beyond the library itself are needed. ```javascript import { getSdkStatus, SdkAvailabilityStatus, } from 'react-native-health-connect'; const checkAvailability = async () => { const status = await getSdkStatus(); if (status === SdkAvailabilityStatus.SDK_AVAILABLE) { console.log('SDK is available'); } if (status === SdkAvailabilityStatus.SDK_UNAVAILABLE) { console.log('SDK is not available'); } if ( status === SdkAvailabilityStatus.SDK_UNAVAILABLE_PROVIDER_UPDATE_REQUIRED ) { console.log('SDK is not available, provider update required'); } }; ``` -------------------------------- ### Open Health Connect Settings Source: https://matinzd.github.io/react-native-health-connect/docs/api/methods/openHealthConnectSettings The `openHealthConnectSettings` function is a void function that opens the Health Connect app's settings screen. It requires no arguments and is used to provide users with direct access to manage their health data permissions. ```javascript import { openHealthConnectSettings } from 'react-native-health-connect'; // ... openHealthConnectSettings(); ``` -------------------------------- ### Background Access Permission Source: https://matinzd.github.io/react-native-health-connect/docs/permissions Information on how to request and implement background access permission, allowing your app to read health data even when not in the foreground. ```APIDOC ## Background Access Permission This permission enables your application to read health data in the background. ### Method `requestPermission` (JavaScript function) ### Endpoint N/A (This is a client-side function call) ### Parameters #### Request Body - **accessType** (string) - Required - Specifies the type of access requested. Use `'read'` for reading data. - **recordType** (string) - Required - The type of record to request permission for. Use `'BackgroundAccessPermission'` for background access. ### Request Example ```javascript requestPermission([ { accessType: 'read', recordType: 'BackgroundAccessPermission', }, // Potentially other permissions... ]); ``` ### Android Manifest Configuration Add the following to your `AndroidManifest.xml`: ```xml ``` ### Note Under the hood, this corresponds to `HealthPermission.PERMISSION_READ_HEALTH_DATA_IN_BACKGROUND` in the Android Health Connect API. ``` -------------------------------- ### Request Exercise Route Permissions (JavaScript/TypeScript) Source: https://matinzd.github.io/react-native-health-connect/docs/api/methods/requestExerciseRoute Requests user permission to access exercise route data for a specific record. This is necessary when the `exerciseRoute.type` indicates `ExerciseRouteResultType.CONSENT_REQUIRED`. It returns a Promise that resolves with the route data if granted, or indicates denial. ```javascript import { requestExerciseRoute, readRecord, ExerciseRouteResultType, } from "react-native-health-connect"; const recordId = "6bd8109d-349b-319a-890a-c5a20902b530"; readRecord("ExerciseSession", recordId) .then((exercise) => { console.log("Exercise record: ", JSON.stringify(exercise, null, 2)); // Check if consent is required to read route: if ( exercise.exerciseRoute.type === ExerciseRouteResultType.CONSENT_REQUIRED ) { requestExerciseRoute(recordId).then(({ route }) => { if (route) { console.log(JSON.stringify(route, null, 2)); } else { console.log("User denied access"); } }); } }) .catch((err) => { console.error("Error reading exercise record", { err }); }); ``` -------------------------------- ### Exercise Route Permission Source: https://matinzd.github.io/react-native-health-connect/docs/api/methods/requestPermission If your app needs to write exercise routes, you can include 'ExerciseRoute' as a special permission in your request. ```APIDOC ## POST /requestPermission (Exercise Route) ### Description Requests permission to read and write exercise session data, including exercise routes. ### Method POST ### Endpoint /requestPermission ### Parameters #### Request Body - **permissions** (Permission[]) - Required - An array of permission objects. Must include `recordType: 'ExerciseRoute'` with `accessType: 'write'` for route writing. ### Request Example ```json { "permissions": [ { "accessType": "read", "recordType": "ExerciseSession" }, { "accessType": "write", "recordType": "ExerciseSession" }, { "accessType": "write", "recordType": "ExerciseRoute" } ] } ``` ### Response #### Success Response (200) - **permissions** (Permission[]) - An array of granted permissions. #### Response Example ```json { "permissions": [ { "accessType": "read", "recordType": "ExerciseSession" }, { "accessType": "write", "recordType": "ExerciseSession" }, { "accessType": "write", "recordType": "ExerciseRoute" } ] } ``` ``` -------------------------------- ### AndroidManifest.xml Permissions for Exercise Routes Source: https://matinzd.github.io/react-native-health-connect/docs/api/methods/requestExerciseRoute Declares the necessary permissions in the AndroidManifest.xml file to allow the application to read exercise routes and general exercise data from Health Connect. These are required before attempting to request user consent. ```xml ... ``` -------------------------------- ### HealthConnectClient getSdkStatus Method Signature (TypeScript) Source: https://matinzd.github.io/react-native-health-connect/docs/api/methods/getSdkStatus This TypeScript signature defines the `getSdkStatus` method for the HealthConnectClient. It takes an optional `providerPackageName` string and returns a Promise that resolves to a number representing the SDK availability status. This signature is essential for understanding the expected input and output of the function. ```typescript getSdkStatus(providerPackageName: string): Promise; ``` -------------------------------- ### Request Background Access Permission Source: https://matinzd.github.io/react-native-health-connect/docs/api/methods/requestPermission Allows requesting permission to read health data in the background. This is crucial for applications that need to monitor health metrics continuously. The `requestPermission` function returns a promise that resolves with the granted permissions, including the 'BackgroundAccessPermission'. ```javascript import { requestPermission } from 'react-native-health-connect'; const requestBackgroundAccess = () => { requestPermission([ { accessType: 'read', recordType: 'BackgroundAccessPermission', }, // Other permissions you need... { accessType: 'read', recordType: 'Steps', }, { accessType: 'read', recordType: 'HeartRate', } ]).then((permissions) => { console.log('Granted permissions ', { permissions }); }); }; ``` -------------------------------- ### Requesting Permissions Source: https://matinzd.github.io/react-native-health-connect/docs/api/methods/requestPermission Request permission for specified record types and access types. This is the primary method for users to grant your application access to their health data. ```APIDOC ## POST /requestPermission ### Description Request permission for specified record types and access types. ### Method POST ### Endpoint /requestPermission ### Parameters #### Request Body - **permissions** (Permission[]) - Required - An array of permission objects, each specifying an `accessType` ('read' or 'write') and a `recordType`. ### Request Example ```json { "permissions": [ { "accessType": "read", "recordType": "ActiveCaloriesBurned" }, { "accessType": "write", "recordType": "ActiveCaloriesBurned" } ] } ``` ### Response #### Success Response (200) - **permissions** (Permission[]) - An array of granted permissions. #### Response Example ```json { "permissions": [ { "accessType": "read", "recordType": "ActiveCaloriesBurned" }, { "accessType": "write", "recordType": "ActiveCaloriesBurned" } ] } ``` ``` -------------------------------- ### Request Background Access Permission in React Native Source: https://matinzd.github.io/react-native-health-connect/docs/api/methods/backgroundAccessPermission This JavaScript code demonstrates how to request the background access permission using the `requestPermission` function from the `react-native-health-connect` library. It specifically requests 'read' access for 'BackgroundAccessPermission'. ```javascript import { requestPermission } from 'react-native-health-connect'; const requestPermissions = () => { requestPermission([ { accessType: 'read', recordType: 'BackgroundAccessPermission', }, // Other permissions... ]).then((permissions) => { console.log('Granted permissions ', { permissions }); }); }; ``` -------------------------------- ### Standard Health Data Permissions Source: https://matinzd.github.io/react-native-health-connect/docs/permissions This section lists the available health data types and their corresponding read and write permissions required by the Health Connect API. ```APIDOC ## Standard Health Data Permissions This table outlines the available health data types and their associated read and write permissions. ### Parameters #### Query Parameters - **recordClassType** (string) - Description of the data type (e.g., ActiveCaloriesBurned). - **readPermissionDeclaration** (string) - The Android permission string required to read this data type (e.g., `android.permission.health.READ_ACTIVE_CALORIES_BURNED`). - **writePermissionDeclaration** (string) - The Android permission string required to write to this data type (e.g., `android.permission.health.WRITE_ACTIVE_CALORIES_BURNED`). ### Response Example ```json [ { "recordClassType": "ActiveCaloriesBurned", "readPermissionDeclaration": "android.permission.health.READ_ACTIVE_CALORIES_BURNED", "writePermissionDeclaration": "android.permission.health.WRITE_ACTIVE_CALORIES_BURNED" }, { "recordClassType": "BasalBodyTemperature", "readPermissionDeclaration": "android.permission.health.READ_BASAL_BODY_TEMPERATURE", "writePermissionDeclaration": "android.permission.health.WRITE_BASAL_BODY_TEMPERATURE" } // ... other record types ] ``` ``` -------------------------------- ### Add Health Connect Permissions to AndroidManifest.xml (React Native CLI) Source: https://matinzd.github.io/react-native-health-connect/docs/permissions This snippet shows how to add necessary permissions for reading and writing health data (heart rate, steps) to the AndroidManifest.xml file. These permissions are essential for your app to interact with the Health Connect service. ```xml + + + + ``` -------------------------------- ### Request Health Connect Permissions Source: https://matinzd.github.io/react-native-health-connect/docs/api/methods/requestPermission Requests read or write access for specified health record types using the `requestPermission` function. This is the primary method for obtaining user consent to access health data. It returns a promise that resolves with the granted permissions. ```javascript import { requestPermission } from 'react-native-health-connect'; const requestPermissions = () => { requestPermission([ { accessType: 'read', recordType: 'ActiveCaloriesBurned', }, { accessType: 'write', recordType: 'ActiveCaloriesBurned', }, ]).then((permissions) => { console.log('Granted permissions ', { permissions }); }); }; ``` -------------------------------- ### Request Exercise Route Permission Source: https://matinzd.github.io/react-native-health-connect/docs/api/methods/requestPermission Enables requesting write access for 'ExerciseRoute' in addition to other permissions like 'ExerciseSession'. This is necessary for apps that need to store exercise route data in Health Connect. The function returns a promise with the granted permissions. ```javascript import { requestPermission } from 'react-native-health-connect'; const requestPermissions = () => { requestPermission([ { accessType: 'read', recordType: 'ExerciseSession', }, { accessType: 'write', recordType: 'ExerciseSession', }, { accessType: 'write', recordType: 'ExerciseRoute' } ]).then((permissions) => { console.log('Granted permissions ', { permissions }); }); }; ``` -------------------------------- ### Aggregate Data by Period - JavaScript Source: https://matinzd.github.io/react-native-health-connect/docs/api/methods/aggregateGroupByPeriod Demonstrates how to use the `aggregateGroupByPeriod` function to read aggregated step data. It specifies the record type, a time range filter, and a time slicer for daily aggregation. The function returns a promise that resolves with an array of aggregated results. ```javascript import { aggregateGroupByPeriod } from 'react-native-health-connect'; const aggregateSampleData = () => { aggregateGroupByPeriod({ recordType: 'Steps', timeRangeFilter: { operator: 'between', startTime: '2024-09-03T15:00', endTime: '2024-09-11T10:50:12.182', }, timeRangeSlicer: { period: 'DAYS', length: 1, }, }).then((result) => { console.log('Aggregated Group by Period: ', { result }); }); }; ``` -------------------------------- ### Retrieve Single Record - TypeScript Source: https://matinzd.github.io/react-native-health-connect/docs/api/methods/readRecord This TypeScript function signature defines how to retrieve a single health record. It takes the record type and record ID as parameters and returns a Promise that resolves with the RecordResult of the specified type. Ensure the correct record type and a valid record ID are provided. ```typescript function readRecord( recordType: T, recordId: string ): Promise>; ``` -------------------------------- ### Background Access Permission Source: https://matinzd.github.io/react-native-health-connect/docs/api/methods/requestPermission If your app needs to read health data in the background, you can request the 'BackgroundAccessPermission'. ```APIDOC ## POST /requestPermission (Background Access) ### Description Requests background read access permission for health data, in addition to other specified read permissions. ### Method POST ### Endpoint /requestPermission ### Parameters #### Request Body - **permissions** (Permission[]) - Required - An array of permission objects. Must include `recordType: 'BackgroundAccessPermission'` with `accessType: 'read'` for background access. ### Request Example ```json { "permissions": [ { "accessType": "read", "recordType": "BackgroundAccessPermission" }, { "accessType": "read", "recordType": "Steps" }, { "accessType": "read", "recordType": "HeartRate" } ] } ``` ### Response #### Success Response (200) - **permissions** (Permission[]) - An array of granted permissions, including background access if granted. #### Response Example ```json { "permissions": [ { "accessType": "read", "recordType": "BackgroundAccessPermission" }, { "accessType": "read", "recordType": "Steps" }, { "accessType": "read", "recordType": "HeartRate" } ] } ``` ``` -------------------------------- ### Open Health Connect Data Management Screen (JavaScript) Source: https://matinzd.github.io/react-native-health-connect/docs/api/methods/openHealthConnectDataManagement The `openHealthConnectDataManagement` function opens the Health Connect data management screen. It is an asynchronous function that does not return a value. It can optionally accept a `providerPackageName` string to specify a particular provider. This function is part of the 'react-native-health-connect' library. ```javascript import { openHealthConnectDataManagement } from 'react-native-health-connect'; // ... openHealthConnectDataManagement(); ``` -------------------------------- ### Read Single Record Source: https://matinzd.github.io/react-native-health-connect/docs/api/methods/readRecord Retrieves a single health record of a specified type using its unique identifier. ```APIDOC ## `readRecord` ### Description Retrieves a single record of the specified type. ### Method `readRecord(recordType: T, recordId: string): Promise>` ### Parameters #### Path Parameters - **recordType** (RecordType) - Required - The type of record to retrieve (e.g., 'ActiveCaloriesBurned'). - **recordId** (string) - Required - The unique identifier of the record. ### Request Example ```javascript import { readRecord } from 'react-native-health-connect'; const readSampleDataSingle = () => { readRecord( 'ActiveCaloriesBurned', 'a7bdea65-86ce-4eb2-a9ef-a87e6a7d9df2' ).then((result) => { console.log('Retrieved record: ', JSON.stringify({ result }, null, 2)); }); }; ``` ### Response #### Success Response (200) - **result** (RecordResult) - The retrieved health record. #### Response Example ```json { "result": { "id": "a7bdea65-86ce-4eb2-a9ef-a87e6a7d9df2", "time": "2023-10-27T10:00:00Z", "endTime": "2023-10-27T10:05:00Z", "duration": 300000, "energy": { "inKilocalories": 10, "inJoules": 41840 } } } ``` ``` -------------------------------- ### Add Health Permissions to app.json (Expo) Source: https://matinzd.github.io/react-native-health-connect/docs/permissions This JSON snippet demonstrates how to declare necessary Health Connect permissions within the app.json configuration file for Expo projects. This approach simplifies permission management using EAS Build and Config plugins. ```json { "expo": { ... "android": { ... "permissions": [ "android.permission.health.READ_STEPS", "android.permission.health.WRITE_STEPS", "android.permission.health.READ_ACTIVE_CALORIES_BURNED" ] }, ... } } ``` -------------------------------- ### Request Background Access Permission - React Native Source: https://matinzd.github.io/react-native-health-connect/docs/permissions This snippet demonstrates how to request background access permission for Health Connect data in a React Native application. It involves adding a permission to the AndroidManifest.xml and then using the requestPermission function with the appropriate access type and record type. ```xml ``` ```javascript // Request background access permission requestPermission([ { accessType: 'read', recordType: 'BackgroundAccessPermission', }, // Other permissions... ]); ``` -------------------------------- ### Read Health Records (TypeScript) Source: https://matinzd.github.io/react-native-health-connect/docs/api/methods/readRecords Retrieves a collection of health records from Health Connect. It requires the record type and read options, including time range and data origin filters. The function returns a Promise that resolves with the retrieved records. ```typescript function readRecords( // record type e.g activeCaloriesBurned recordType: T, // read options such as time range filter, data origin filter, ordering and pagination options: ReadRecordsOptions ): Promise>; ``` ```javascript import { readRecords } from 'react-native-health-connect'; const readSampleData = () => { readRecords('ActiveCaloriesBurned', { timeRangeFilter: { operator: 'between', startTime: '2023-01-09T12:00:00.405Z', endTime: '2023-01-09T23:53:15.405Z', }, }).then(({ records }) => { console.log('Retrieved records: ', JSON.stringify({ records }, null, 2)); }); }; ``` -------------------------------- ### Check Background Access Permission Status in React Native Source: https://matinzd.github.io/react-native-health-connect/docs/api/methods/backgroundAccessPermission This JavaScript code shows how to check if the background access permission has been granted using the `getGrantedPermissions` function. It filters the granted permissions to specifically look for read access to 'BackgroundAccessPermission'. ```javascript import { getGrantedPermissions } from 'react-native-health-connect'; const checkBackgroundAccess = async () => { const permissions = await getGrantedPermissions(); const hasBackgroundAccess = permissions.some( (permission) => permission.accessType === 'read' && permission.recordType === 'BackgroundAccessPermission' ); console.log('Has background access:', hasBackgroundAccess); }; ``` -------------------------------- ### Add Background Health Data Read Permission to AndroidManifest.xml Source: https://matinzd.github.io/react-native-health-connect/docs/api/methods/backgroundAccessPermission This XML snippet shows how to declare the `android.permission.health.READ_HEALTH_DATA_IN_BACKGROUND` permission in your Android app's `AndroidManifest.xml` file. This is a prerequisite for requesting background access to health data. ```xml ```