Get started

This guide shows you how you can start using the Health Connect API on your app.

Resources

Before you begin, you can check out the following resources that help with development later on.

  • Health Connect SDK (available on Jetpack). Include this SDK in your application to use the Health Connect API.
  • API reference. Take a look at the Jetpack reference for the Health Connect API.
  • API Request Developer Declaration Form. Use this form to request access to read and write data types.
  • Optional: Github code sample and codelab. See the Github code sample repository and the codelab to help you get started.

Step 1: Install Health Connect

Install Health Connect by Android from the Google Play Store to your device. It handles all requests sent by your application using the Health Connect SDK.

After installation

Health Connect no longer appears on the Home screen by default. To open Health Connect, go to Settings > Apps > Health Connect or add Health Connect to your Quick Settings menu.

To add, Health Connect requires the user to have screen lock enabled with a PIN, pattern, or password so that the health data being stored in Health Connect is protected from malicious parties while the device is locked. To set a screen lock, go to Settings > Security > Screen lock.

Step 2: Add the Health Connect SDK to your application

Add a dependency on the Health Connect SDK in your module-level build.gradle file:

dependencies {
  ...
  implementation "androidx.health.connect:connect-client:1.0.0-alpha11"
  ...
}

Refer to the Health Connect releases for the latest version.

Step 3: Get Health Connect client

HealthConnectClient is an entry point to the Health Connect API.

This step explains the process of integrating the app with Health Connect to use its features.

  1. Declare the Health Connect package name in your AndroidManifest.xml file.

    <!-- Check whether Health Connect is installed or not -->
    <queries>
        <package android:name="com.google.android.apps.healthdata" />
    </queries>
    
  2. Check if Health Connect is installed. If it is, obtain a HealthConnectClient instance.

    If you are using alpha11 or higher versions, use sdkStatus. The following example shows how to check if the SDK is available, if it needs updates, or if it is unavailable.

    val availabilityStatus = HealthConnectClient.sdkStatus(context, providerPackageName)
    if (availabilityStatus == HealthConnectClient.SDK_UNAVAILABLE) {
      return // early return as there is no viable integration
    }
    if (availabilityStatus == HealthConnectClient.SDK_UNAVAILABLE_PROVIDER_UPDATE_REQUIRED) {
      // Optionally redirect to package installer to find a provider, for example:
      val uriString = "market://details?id=$providerPackageName&url=healthconnect%3A%2F%2Fonboarding"
      context.startActivity(
        Intent(Intent.ACTION_VIEW).apply {
          setPackage("com.android.vending")
          data = Uri.parse(uriString)
          putExtra("overlay", true)
          putExtra("callerId", context.packageName)
        }
      )
      return
    }
    val healthConnectClient = HealthConnectClient.getOrCreate(context)
    // Issue operations with healthConnectClient
    

    If you are using versions between alpha08 and alpha10, use isProviderAvailable. The following example shows how to implement it.

    if (HealthConnectClient.isProviderAvailable(context)) {
      // Health Connect is available and installed.
      val healthConnectClient = HealthConnectClient.getOrCreate(context)
    } else {
      // ...
    }
    
  3. The client app must request permission from the user. The user can grant or deny access to the client app at any point.

HealthConnectClient automatically manages its connection to the underlying storage layer and handles all IPC and serialization of outgoing requests and incoming responses.

Step 4: Declare permissions

Every data type your app reads or writes needs to be declared using a permission in your manifest. In this step, the configuration differs depending on which SDK version you use.

For more information about how permissions are managed, prompted, requested, declared, and revoked in Health Connect, see Managing permissions in Health Connect.

For 'alpha10' and higher versions

On versions alpha10 and higher, Health Connect uses the standard Android permission declaration format.

  1. To declare the permissions for the required data types, use the <uses-permission> tags and assign their respective names with the permissions. Nest them within the <manifest> tags.

    <manifest>
      <uses-permission android:name="android.permission.health.READ_HEART_RATE"/>
      <uses-permission android:name="android.permission.health.WRITE_HEART_RATE"/>
      <uses-permission android:name="android.permission.health.READ_STEPS"/>
      <uses-permission android:name="android.permission.health.WRITE_STEPS"/>
    
      <application>
      ...
      </application>
    </manifest>
    

    For the full list of permissions and their corresponding data types, see List of data types.

  2. Explain how your app uses Health Connect.

    Your manifest needs to provide <activity> which displays the privacy policy describing how the user's data is used and handled. You can either add a new <activity> or modify an existing one.

    This activity needs to declare that it handles the ACTION_SHOW_PERMISSIONS_RATIONALE intent. This intent is sent to the app when the user clicks on the Read privacy policy link in the Health Connect permissions dialog.

    ...
    <uses-permission android:name="android.permission.health.READ_HEART_RATE"/>
    <uses-permission android:name="android.permission.health.WRITE_HEART_RATE"/>
    <uses-permission android:name="android.permission.health.READ_STEPS"/>
    <uses-permission android:name="android.permission.health.WRITE_STEPS"/>
    
    <application>
      ...
      <!-- Activity to show rationale of Health Connect permissions -->
      <activity
        android:name=".PermissionsRationaleActivity"
        android:exported="true"
        android:enabled="true">
        <!-- Handle intent -->
        <intent-filter>
          <action android:name="androidx.health.ACTION_SHOW_PERMISSIONS_RATIONALE" />
        </intent-filter>
      </activity>
      ...
    </application>
    ...
    

For 'alpha09' and lower versions

On versions alpha09 and lower, Health Connect uses a list of values from the resources folder containing the health permissions.

  1. To declare the permissions for the data types required, create an array resource in res/values.

    <resources>
      <array name="health_permissions">
        <item>androidx.health.permission.HeartRate.READ</item>
        <item>androidx.health.permission.HeartRate.WRITE</item>
        <item>androidx.health.permission.Steps.READ</item>
        <item>androidx.health.permission.Steps.WRITE</item>
      </array>
    </resources>
    

    For the full list of permissions and their corresponding data types, see List of data types.

  2. Explain how your app uses Health Connect.

    Your manifest needs to provide <activity> which displays the privacy policy describing how the user's data is used and handled. You can either add a new <activity> or modify an existing one.

    This activity needs to reference the array resource you created to declare the set of permissions. Then, declare that it handles the ACTION_SHOW_PERMISSIONS_RATIONALE intent. This intent is sent to the app when the user clicks on the Read privacy policy link in the Health Connect permissions dialog.

    <application>
      ...
      <!-- Activity to show rationale of Health Connect permissions -->
      <activity
        android:name=".PermissionsRationaleActivity"
        android:exported="true"
        android:enabled="true">
        <!-- For alpha09 and lower, reference permissions resource -->
        <meta-data
          android:name="health_permissions"
          android:resource="@array/health_permissions" />
        <!-- Handle intent -->
        <intent-filter>
          <action android:name="androidx.health.ACTION_SHOW_PERMISSIONS_RATIONALE" />
        </intent-filter>
      </activity>
      ...
    </application>
    

Hide Health Connect integration

When the Activity that exposes ACTION_SHOW_PERMISSIONS_RATIONALE is enabled, your app automatically appears in Health Connect as available. However, there are some scenarios where you need to hide the Health Connect integration until it is ready for launch.

In order to hide the integration, set the enabled attribute of that Activity to false.

<activity
  android:name=".PermissionsRationaleActivity"
  android:exported="true"
  android:enabled="false">
  ...
</activity>

When you're ready to turn it on, dynamically enable it in your app using PackageManager.setComponentEnabledSetting.

Step 5: Request permissions from the user

This step explains how to display the permission dialog.

  1. Build a set of permissions for the required data types. Ensure that the permissions in the set are declared in your manifest first.

    The manner of building the permission set differs depending on the SDK version used.

    For alpha10 and higher versions:

    // build a set of permissions for required data types
    // Each permission value is a string data type
    val PERMISSIONS =
    setOf(
      HealthPermission.getReadPermission(HeartRateRecord::class),
      HealthPermission.getWritePermission(HeartRateRecord::class),
      HealthPermission.getReadPermission(StepsRecord::class),
      HealthPermission.getWritePermission(StepsRecord::class)
    )
    

    For alpha09 and lower versions:

    // build a set of permissions for required data types
    // Each permission value is a string data type
    val PERMISSIONS =
    setOf(
      HealthPermission.createReadPermission(HeartRateRecord::class),
      HealthPermission.createWritePermission(HeartRateRecord::class),
      HealthPermission.createReadPermission(StepsRecord::class),
      HealthPermission.createWritePermission(StepsRecord::class)
    )
    
  2. Use getGrantedPermissions() to see if your app already has the required permissions. If not, use the createRequestPermissionResultContract() method to request permission.

    // Create the permissions launcher.
    val requestPermissionActivityContract = PermissionController.createRequestPermissionResultContract()
    
    val requestPermissions =
    registerForActivityResult(requestPermissionActivityContract) { granted ->
     if (granted.containsAll(PERMISSIONS)) {
        // Permissions successfully granted
        // PERMISSIONS: Set<string> as of Alpha11
      } else {
        // Lack of required permissions
      }
    }
    
    suspend fun checkPermissionsAndRun(healthConnectClient: HealthConnectClient) {
      // For alpha09 and lower versions, use getGrantedPermissions(PERMISSIONS) instead
      val granted = healthConnectClient.permissionController.getGrantedPermissions()
      if (granted.containsAll(PERMISSIONS)) {
        // Permissions already granted; proceed with inserting or reading data.
      } else {
        requestPermissions.launch(PERMISSIONS)
      }
    }
    

If the user declines your permission request twice, your app is permanently locked out and it cannot request permissions again. If this happens to your app during development and testing, you can reset the permission request count with these steps:

  1. Open the Health Connect app.
  2. Go to App permissions.
  3. Choose your app.
  4. Toggle Allow all.
  5. Toggle Allow all again to remove all permissions.
  6. When the prompt appears, choose Remove all.

Alternatively use adb to clear the cache of the Health Connect package.

Users can grant or revoke permissions using the Health Connect app at any time. Don't assume that the set of granted permissions does not change. Your app needs to periodically check for granted permissions, and handle scenarios where permission is unexpectedly lost.

Health data is sensitive. To maintain user trust, only request permission to access data in context. Don't request data that your app doesn't use.

Next steps

Watch these two videos that explain how to read and write data in Health Connect, and some best practice guidelines for achieving a smooth integration:

Check out the common workflows for examples on how to perform CRUD operations in Health Connect, such as writing and reading health data.