A couple weeks ago, we were invited to speak at Droidcon, a global conference series for Android developers. This conference brings together developers from all over the world to learn about the latest Android technologies and best practices. Droidcon features a variety of sessions, workshops, and networking opportunities.

What did we talk about?

Gaston, our CTO, spoke about Innovating with Health Connect and did a deep dive into its key benefits.

Android's Health Connect platform allows health and fitness apps to share on-device data within a unified ecosystem. The API allows Android developers to read and write user health and fitness data. Android users can control which apps have access to their health and fitness information.

There are a wide variety of devices and platforms in the Android ecosystem, including smartphones, wearables, and health, fitness, and wellness apps. Android APIs support a variety of data types to accommodate these technologies. Android users want to control their health and fitness data from a single repository in a secure and convenient manner.

With Health Connect, users can track all health and wellness activities across the following key data categories:

  1. Activity tracks any activity a user performs, such as swimming, running, or cycling.
  2. Body Measurement records typical information pertaining to an individual's physique, such as their weight or basal metabolic rate.
  3. Cycle Tracking collects information regarding menstrual cycles, such as the binary result of an ovulation test.
  4. Nutrition gathers various data types concerning hydration and nutrition, encompassing optional fields such as calorie consumption, sugar intake, and magnesium content.
  5. Sleep captures interval data that is related to the type and length of a user's sleep.
  6. Vitals collects vital information regarding the user's overall health, encompassing a wide range of data points such as blood glucose levels, body temperature, and blood oxygen saturation.

The key benefits are:

  • Reduction of API Complexity
  • Standardize Data Scheme
  • Centralize Privacy Controls

Reduction of API Complexity

Health Connect has been working on facilitating and creating a convenient integration between the client apps and the Health Connect API. They brought together Fitbit, Google Fit and Samsung Health under this new API.

In order to understand how they reduced the api complexity we should take a look at its components:

Screenshot-2023-06-19-at-14.50.37-1

The first one is the software development kit. The SDK enables the client app to communicate with the Health Connect APK, over IPC (inter process communication).

The second component are the client apps, these are health and wellness apps such as My Fitness Pal, Flo Health, and Strava where you should link the SDK which facilitates the interaction with the Health Connect API.

The third component is the Health Connect APK/APP. The Health Connect APP is the implementation of the Health Connect API, and contains both its Permissions Management and Data Management components. This app is also available directly on the user’s device, it is able to be downloaded from the play store now, but in the future it will become part of Android 14 as an Android system app.

Health Connect helps visualize the list of apps requesting user's permission to display data as well as a list of existing user permissions such as: heart rate, steps, calories burned, etc.

For data management it provides a user interface with an overview of the recorded data.

Standardized Data Scheme

Before, developers struggled with API fragmentation on Android because of different schemes and different behaviors. Health Connect solves this with a new and unified API. It stores and structures health and fitness data and includes a wide variety of data types commonly used across most health and fitness apps.

Each data type is defined by its data format, which includes the following:

  • Fields: includes specific or generic fields relevant to the data type, such as title, notes, and percentage.
  • Type: Long, double, String, or enumAttribute: Read-only, required, optional, or validation range.
  • Attribute: Read-only, required, optional, or validation range.

Screenshot-2023-06-19-at-14.51.01

Standardized data scheme means that developers can be confident that the data they are getting is in a consistent format. This makes it easier for them to build health apps that are interoperable with other apps and services. It accounts for how different data types, such as steps taken over time, or heart rate measurements taken immediately, are measured.

Centralize Privacy Controls

Users need to stay in control of their privacy and know that their data is secure. For that reason, privacy controls are at the heart of this solution, with users being able to manage the access to their data on a granular level.

Screenshot-2023-06-19-at-14.51.13

How to set up your app with Health Connect?

We saw the key benefits of this solution but let us show you how the magic works!

Users will need to have a relatively modern version of Android as the Health Connect App is compatible with Android Pie (Android 9 / API 28) and higher. Further, your app will need to have a minSdkVersion set to 26 as this is what Health Connect SDK supports.

To start your integration, you will first need to make sure you have the Health Connect App installed from the Play Store. Next, you will have to add the Health Connect SDK dependency to your buil.gradle file.

dependencies {
    implementation 'androidx.health:health-connect-client:1.0.0-alpha03'
}

Also, you must check if Health Connect is installed and available. Since this is pretty new Google is asking developers to promote Health Connect via promo cards and also tell users about the insights they can gain by sharing their data. Nevertheless, the long-term goal is that Health Connect will be pre installed in newer Android versions.

In order to make sure of this, you need to run some availability checks:

  1. First, you have to specify the app to access Health Connect. To do so, you will need to add a query to the Android manifest to check whether Health Connect is installed or not.
<!-- To check whether Health Connect is installed or not -->
<queries> 
    <package android:name="com.google.android.apps.healthdata"/>
</queries>

2. Second, you need to check if Health Connect is supported and installed. In order to do this, we will check if Health Connect is available and if it is, we will request a reference to a HealthConnectClient object.

// Check if Health Connect is available / installed.
fun checkAvailability() {
    when {
        HealthConnectClient.isAvailable(context) -> {
            // Health Connect is supported and installed.
            val healthConnectClient = HealthConnectClient.getOrcreate(context)
        }
        Build.VERSION.SDK_INT < Build.VERSION_CODES.P -> {
            // Health Connect is not supported
        }
        else -> {
            // Health Connect is not installed. 
            installHealthConnect()
        }
    }
}

Conversely, if Health Connect isn’t available you will need to run some additional checks to see if it’s supported. If Health Connect needs to be installed, then you need to redirect users to go through the installation flow.

// Redirect users to Play Store to install Health Connect.
// Include intent to redirect users to 3P app post-Health Connect onboarding flow.
fun installHealthConnect {
    val intent = Intent(Intent.ACTION_VIEW)
    intent.setPackage("com.android.vending")
    intent.data = Uri.parse("market://details")
        .buildUpon()
        .appendQueryParameter("id", "com.google.android.apps.healthdata")
        .appendQueryParameter("url", "healthconnect://onboarding")
        .build()
    context.startActivity(intent)
}

Once this is assured, the next step is to request the user's permission to read and/or write the health and fitness data you would like to interact with. Health Connect also allows you to see what permissions have already been granted or denied by the user.

Screenshot-2023-06-20-at-14.29.00

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. The standard Android declaration format is used by Health Connect for versions alpha10 and higher. Health Connect supports over 50 data types across 6 categories (you can access the full list here.)

<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"/>
</manifest>

Your manifest will also need to display the privacy policy explaining how user data is handled. This can be done by adding a new activity that includes this description or by modifying an existing one. To handle the ACTION_SHOW_PERMISSIONS_RATIONALE intent, the activity must declare its capability. This intent is dispatched to the application when the user interacts with the "Read privacy policy" link within 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="android.health.ACTION_SHOW_PERMISSIONS_RATIONALE"/>
        </intent-filter>
    </activity>

</application>

The final step of the set up consists of requesting permission from the user, by displaying a permission dialog that will need to consider all the required data types. The way to build the permission sets will also depend on the SDK version that you are using.

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

Lastly, you will need to use the getGrantedPermissions() method to check if your app already possesses the necessary permissions. In the event that the required permissions are not granted, you can employ the createRequestPermissionResultContract() method to request them.

Users can revoke permissions at any time, by removing them all together or selecting the data type they want to make unavailable. It is crucial not to assume that the set of granted permissions remains constant. To account for situations where permission is unexpectedly revoked, your app should regularly check for granted permissions and handle such scenarios accordingly.

Screenshot-2023-06-20-at-14.27.37

Also, users have the option to delete data in different levels: all data, per category, app data, or even a single entry, which is also something to take into consideration when building your application.

Screenshot-2023-06-20-at-14.25.46

For more information on this you can check out the Android Developers official youtube video.

We believe the real power is in combining information to get even more accurate and powerful insights. With the apps we have today we can answer questions such as:

  • Have I met my activity goals for today?
  • How well did I sleep last night?
  • How is my weight trending?

But this information is MUCH MORE powerful when COMBINED:

  • Based on my vitals, am I ready for a high intensity workout or just a walk?
  • When I meditate before bed do I fall asleep more easily?
  • Is my fitness & nutrition plan helping me reach my goals?

In conclusion, Health Connect is a very powerful tool we have at our fingertips and we must leverage this data in order to make informed decisions regarding our health.