Reading Body Composition Data with Galaxy Watch via Health Connect API
Samsung Developer
The body composition measurement is one of the powerful features of Samsung Galaxy Watch. It is an important metric of your overall health. The body composition measurement data is displayed in the Samsung Health application on the Galaxy Watch and a compatible smartphone. In this article, we show you how to read the Galaxy Watch’s body composition data using the Android Health Connect API in a sample application named "BIA Viewer". You can download the code for this sample application from the link at the bottom of this blog. BIA is an abbreviation for Bioelectrical Impedance Analysis, and the BIA data measures body composition data.
Installing Health Connect API
The Android Health Connect API provides interfaces for reading and writing your health and fitness data. The Samsung Health application exchanges data with the Health Connect API. For more information, see Accessing Samsung Health Data through Health Connect.
Measuring body composition with Galaxy Watch
As the first step in developing your ultimate health application, you must collect the body composition data using the Samsung Health application in Galaxy Watch.
Steps to measure BIA with Galaxy Watch:
- Start the Samsung Health application.
- Ensure that the Galaxy Watch is worn tightly on your wrist.
- Raise your arms so your armpits are open.
- Place your middle finger on the 2 o’clock key and ring finger on the 4 o’clock key on the watch.
- Touch your watch only. Don’t let your hand on the watch’s keys touch your arm or other hand on the watch.
- Maintain the finger positions on the Galaxy Watch dial until the measurement is completed.
Example of a result obtained by measuring body composition with the Samsung Health application:
After the BIA measurement is completed on the Galaxy Watch, the data can be synchronized with the Samsung Health application.
Synchronizing data with the Health Connect application
Once you have data in the Samsung Health application, it is synchronized with the Health Connect application. Synchronized body composition data can be found directly in the Health Connect application.
- Basal metabolic rate
- Body fat
- Height
- Weight
BIA Viewer application overview
BIA Viewer is an application that reads the body composition data collected by the Samsung Health application with the Health Connect APIs. By default, this application loads the data during startup. However, you can manually reload the data using the “Refresh” button. The BIA Viewer application reads the body composition data such as weight, height, body fat, basal metabolic rate. The user's height is not displayed and is only used to calculate BMI. The step-by-step construction of the most important elements of the application are described in the next sections.
- Fat mass is calculated using the formula: [Fat mass] = [Body Fat] * [Weight] / 100
- BMI is calculated using the formula: [BMI] = [Weight] / ([Height]* [Height])
Adding Health Connect API to your project
Before you start writing your code, you need to import and add the Health Connect API library to the file application/build.gradle in the dependencies section.
implementation 'androidx.health.connect:connect-client:1.1.0-alpha06'
Now you are ready to use the Health Connect API.
Checking Health Connect availability on your device
At the beginning of your application, it's a good idea to ensure that the device running your application actually supports the Health Connect API library. The library is available only when the Health Connect application is installed on the device.
private fun checkAvailability(): Boolean {
when (HealthConnectClient.getSdkStatus(this)) {
HealthConnectClient.SDK_UNAVAILABLE -> {
//Error message – unable to install Health Connect
}
return false
}
HealthConnectClient.SDK_UNAVAILABLE_PROVIDER_UPDATE_REQUIRED -> {
//Error message – Health Connect not present on device, but can be installed
}
return false
}
else -> {
return true
}
}
}
Get HealthConnectClient
Before going to the next step, you need to get HealthConnectClient. HealthConnectClient is an entry point to the Health Connect API. HealthConnectClient automatically manages its connection to the underlying storage layer and handles all IPC and serialization of the outgoing requests and the incoming responses.
private val healthConnectClient by lazy { HealthConnectClient.getOrCreate(context) }
Ask for permissions
In the first step, you need to modify the AndroidManifest.xml file.
- Add
<intent-filter>
in the<activity>
section:
<intent-filter>
<action android:name="androidx.health.ACTION_SHOW_PERMISSIONS_RATIONALE" />
</intent-filter>
- Add
<activity-alias>
element required in 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>
- Add
<uses-permission>
elements:
<uses-permission android:name="android.permission.health.READ_BASAL_METABOLIC_RATE" />
<uses-permission android:name="android.permission.health.READ_BODY_FAT" />
<uses-permission android:name="android.permission.health.READ_HEIGHT" />
<uses-permission android:name="android.permission.health.READ_WEIGHT" />
- Add
<queries>
elements:
<queries>
<package android:name="com.google.android.apps.healthdata" />
</queries>
To start the request permissions from your application, first build a set of permissions for the required data types. Make sure to only ask for permissions mentioned in the Manifest file.
val permissions = setOf(
HealthPermission.getReadPermission(BasalMetabolicRateRecord::class),
HealthPermission.getReadPermission(BodyFatRecord::class),
HealthPermission.getReadPermission(HeightRecord::class),
HealthPermission.getReadPermission(WeightRecord::class),
)
It is a good practice to ask for the required permissions whenever the application tries to use this data type. First, you should check whether the user has consented to use the particular functionality.
suspend fun hasAllPermissions(): Boolean {
return healthConnectClient.permissionController.getGrantedPermissions()
.containsAll(permissions)
}
If not, you should ask for it before using the API.
private fun checkPermissions() {
lifecycleScope.launch {
if (healthConnectManager.hasAllPermissions()) {
readAllData()
} else {
requestPermissions.launch(healthConnectManager.permissions)
}
}
}
To ask for permissions, you need to create a request permissions object.
private fun createRequestPermissionsObject() {
requestPermissions =
registerForActivityResult(healthConnectManager.requestPermissionActivityContract) { granted ->
lifecycleScope.launch {
if (granted.isNotEmpty() && healthConnectManager.hasAllPermissions()) {
Toast.makeText(
this@MainActivity,
R.string.permission_granted,
Toast.LENGTH_SHORT,
).show()
} else {
AlertDialog.Builder(this@MainActivity)
.setMessage(R.string.permission_denied)
.setPositiveButton(R.string.ok, null)
.show()
}
}
}
}
Sample permission request window:
Creating a query to read body composition data
To read data, build the ReadRecordsRequest object and in the parameters, specify the time range and the data type. Then, read the data by passing the ReadRecordsRequest object as a parameter. After the request is finished, the result contains the list of returned data that you requested. Then you go through the list and read individual records. In our example, we will read only the last value.
ReadRecordsRequest example code for WeightRecord data type:
suspend fun readWeight(start: Instant, end: Instant): Double {
val request = ReadRecordsRequest(
recordType = WeightRecord::class,
timeRangeFilter = TimeRangeFilter.between(start, end)
)
val response = healthConnectClient.readRecords(request)
if (response.records.isNotEmpty()) {
val weightRecord = response.records.last()
return weightRecord.weight.inKilograms
}
return 0.0
}
List of all the data types used in the application:
BasalMetabolicRateRecord
BodyFatRecord
HeightRecord
WeightRecord
Checking query results
Now you are ready to run the test application on your phone and compare the results of the application with the Samsung Health application. The application can be tested on the device by running it directly from Android Studio.
The data in both pictures are identical. You were able to successfully recover the data from the Samsung Health application using the Health Connect API.
Resources
This blog is based on the BIA Viewer application. The entire code in this blog comes from this application. The application can be downloaded from:
Enjoy your adventure creating the ultimate health application
Now you are ready to start using the Samsung Health application with the Health Connect API to enhance the capabilities of your application.