react-native-health-connect

repository·main·Indexed 19 days ago

https://github.com/matinzd/react-native-health-connect

A React Native wrapper for the Android Health Connect API (Android only) that allows developers to read and write health and fitness data. It supports standard React Native CLI and Expo managed workflow (via custom development builds), providing methods for initializing the client, managing permissions, inserting records, and reading or aggregating health data.

Tokens
26.6K
Snippets
73
Records
90
Agent score
65%

What's inside react-native-health-connect

  1. Introduction to React Native Health Connect

    main

    React Native Health Connect is a wrapper around the Android Health Connect API. It provides a unified interface for React Native applications to read and write a user's health and fitness data on Android devices.

    Key Considerations:

    • Platform Support: This library is Android only.
    • Health Connect Status: Health Connect is currently in its alpha channel. Developers should monitor the official Jetpack releases for updates.
    • Permission Behavior: If a user declines a permission request twice, the app is permanently locked out from requesting those permissions again. You must handle these permission states gracefully in your UI.
  2. Handle upserted record data formats

    main

    Records returned in upsertionChanges are serialized in the same format as readRecords results. This means unit-bearing fields use the *Result variant (providing multiple unit conversions) rather than a simple { value, unit } object.

    For example, a Weight record will provide fields like inKilograms, inGrams, etc. To access specific values, you should check the recordType and then access the corresponding unit field.

    Example: Extracting Weight in Kilograms

    const weightsInKilograms = upsertionChanges.flatMap(({ record }) =>
      record.recordType === 'Weight' ? [record.weight.inKilograms] : []
    );
    // Example of the data structure returned for a Weight record
    {
      "recordType": "Weight",
      "weight": {
        "inGrams": 75000,
        "inKilograms": 75,
        "inMilligrams": 75000000,
        "inMicrograms": 75000000000,
        "inOunces": 2645.5474378402178,
        "inPounds": 165.3466966386582
      }
    }
  3. Important considerations for Background Access Permission

    main

    When implementing background access, keep the following in mind:

    • User Transparency: Background access is a powerful permission. You should clearly explain to users why your app requires access to their health data while not in the foreground.
    • Platform Availability: This permission is only available on Android devices that support Health Connect.
    • Android Mapping: This permission maps to HealthPermission.PERMISSION_READ_HEALTH_DATA_IN_BACKGROUND in the underlying Android Health Connect API.
  4. Requirements for react-native-health-connect

    main

    Before installing, ensure your environment meets these criteria:

    • React Native: Version 0.71 or higher (with the latest patch) is required for v2.
    • Android SDK: minSdkVersion must be set to 26 (Android Oreo / 8.0) or higher.
    • Health Connect App: The Health Connect app must be installed on the user's device. On Android 14+, it is integrated into the Android Framework.
    • Device Security: The user must have a screen lock (PIN, pattern, or password) enabled to protect health data.
    • Google Play Declaration: If releasing on Google Play, you must declare Health Connect data access via the Play Console. Approval can take up to 7 days, plus an additional 5-7 business days for whitelist propagation to Health Connect servers.
  5. Install and configure for Expo (Managed Workflow)

    main

    This package cannot be used in the Expo Go app; it requires a custom development build. As of v4, Expo integration is built into react-native-health-connect.

    1. Install the package and expo-build-properties:
    npm install react-native-health-connect
    npm install expo-build-properties --save-dev
    1. Add the config plugins to your app.json or app.config.js. Note that minSdkVersion must be at least 26.

    2. Run npx expo prebuild and rebuild your app (e.g., yarn android).

    3. Create a new EAS development build:

    eas build --profile development --platform android
    {
      "expo": {
        "plugins": [
          "react-native-health-connect",
          [
            "expo-build-properties",
            {
              "android": {
                "compileSdkVersion": 36,
                "targetSdkVersion": 36,
                "minSdkVersion": 26
              }
            }
          ]
        ]
       }
    }
  6. Set up permissions in React Native CLI

    main

    To access Health Connect data in a React Native CLI project, you must configure the Android manifest to include specific permissions and handle permission rationale activities for different Android versions.

    1. Add permissions to android/src/main/AndroidManifest.xml using the android.permission.health.* format.
    2. Create a Rationale Activity: For Android versions up to 13, you must implement a PermissionRationaleActivity.kt to show users why you need access when they click privacy policy links.
    3. Configure Intent Filters:
      • Add androidx.health.ACTION_SHOW_PERMISSIONS_RATIONALE to your MainActivity intent filter (for Android 13 and below).
      • Add a new PermissionsRationaleActivity with the same action.
      • For Android 14+, add an <activity-alias> named ViewPermissionUsageActivity targeting your MainActivity with the android.permission.START_VIEW_PERMISSION_USAGE permission.
    <!-- Example permissions in AndroidManifest.xml -->
    <uses-permission android:name="android.permission.health.READ_HEART_RATE"/>
    <uses-permission android:name="android.permission.health.WRITE_HEART_RATE"/>
    
    <!-- Activity for rationale (Android 13 and below) -->
    <activity
      android:name=".PermissionsRationaleActivity"
      android:exported="true">
      <intent-filter>
        <action android:name="androidx.health.ACTION_SHOW_PERMISSIONS_RATIONALE" />
      </intent-filter>
    </activity>
    
    <!-- Activity alias (Android 14+) -->
    <activity-alias
      android:name="ViewPermissionUsageActivity"
      android:exported="true"
      android:targetActivity=".MainActivity"
      android:permission="android.permission.START_VIEW_PERMISSION_USAGE">
      <intent-filter>
        <action android:name="android.intent.action.VIEW_PERMISSION_USAGE" />
        <category android:name="android.intent.category.HEALTH_PERMISSIONS" />
      </intent-filter>
    </activity-alias>
  7. Configure Background Access Permission for Health Connect

    main

    To allow your app to read health data while running in the background (e.g., for continuous fitness tracking), you must perform a two-step setup: declaring the permission in your Android manifest and requesting it via the library API.

    1. Android Manifest Declaration

    Add the following permission to your android/app/src/main/AndroidManifest.xml file:

    <uses-permission android:name="android.permission.health.READ_HEALTH_DATA_IN_BACKGROUND"/>

    2. Requesting Permission in Code

    Include the BackgroundAccessPermission in your requestPermission call. You must specify the accessType as 'read' and the recordType as 'BackgroundAccessPermission'.

    import { requestPermission } from 'react-native-health-connect';
    
    const requestPermissions = () => {
      requestPermission([
        {
          accessType: 'read',
          recordType: 'BackgroundAccessPermission',
        },
        // Other permissions...
      ]).then((permissions) => {
        console.log('Granted permissions ', { permissions });
      });
    };
  8. Manage changes token expiration and lifecycle

    main

    Changes tokens are only valid for 30 days. To prevent data loss or sync failures, your application should implement the following:

    1. Regular Updates: Regularly call getChanges to process updates within the 30-day window to avoid tokens becoming stale.
    2. Expiration Handling: Monitor the changesTokenExpired flag in the response. If true, the token is no longer valid.
    3. Fallback Mechanism: Implement a fallback strategy (such as a full readRecords sync) to obtain necessary data if the token expires or becomes invalid.
  9. Run the Expo example project

    main

    The example-expo directory is a standalone Yarn project. To run the example using Expo SDK 57, follow these steps to install dependencies, perform a clean prebuild for Android, and launch the application.

    Note that the android/ directory is gitignored and must be regenerated using prebuild if it is missing or needs resetting.

    cd example-expo
    yarn install
    npx expo prebuild --clean --platform android
    npx expo run:android