Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
110 changes: 87 additions & 23 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ Official notes ([full changelog](https://developer.android.com/jetpack/androidx/
| **1.2.0-alpha01** | 2025-07-30 | Skin temperature / mindfulness compat; activity intensity (Android 14+) |
| **1.1.0** (stable) | 2025-10-08 | First stable `connect-client` |

JS API still covers the [19 record types](#supported-record-types) below. Alpha-only APIs (matchmaking, mindfulness, skin temperature, activity intensity, PHR) are **not** wrapped yet.
JS API covers the [22 record types](#supported-record-types) below, plus feature checks, Matchmaking, and Personal Health Record (PHR) helpers. Feature-gated types require `getFeatureStatus(...) === 'available'` on the device.

## Installation

Expand Down Expand Up @@ -271,27 +271,77 @@ await deleteRecordsById('Steps', ['record-id-1', 'record-id-2']);

## Supported record types

| Record type | Read | Write |
|---|---|---|
| `Steps` | ✅ | ✅ |
| `HeartRate` | ✅ | ✅ |
| `SleepSession` | ✅ | ✅ |
| `ActiveCaloriesBurned` | ✅ | ✅ |
| `TotalCaloriesBurned` | ✅ | ✅ |
| `Distance` | ✅ | ✅ |
| `Weight` | ✅ | ✅ |
| `Height` | ✅ | ✅ |
| `BloodPressure` | ✅ | ✅ |
| `BloodGlucose` | ✅ | ✅ |
| `OxygenSaturation` | ✅ | ✅ |
| `BodyTemperature` | ✅ | ✅ |
| `BodyFat` | ✅ | ✅ |
| `Hydration` | ✅ | ✅ |
| `ExerciseSession` | ✅ | ✅ |
| `RestingHeartRate` | ✅ | ✅ |
| `RespiratoryRate` | ✅ | ✅ |
| `FloorsClimbed` | ✅ | ✅ |
| `ElevationGained` | ✅ | ✅ |
| Record type | Read | Write | Notes |
|---|---|---|---|
| `Steps` | ✅ | ✅ | |
| `HeartRate` | ✅ | ✅ | |
| `SleepSession` | ✅ | ✅ | |
| `ActiveCaloriesBurned` | ✅ | ✅ | |
| `TotalCaloriesBurned` | ✅ | ✅ | |
| `Distance` | ✅ | ✅ | |
| `Weight` | ✅ | ✅ | |
| `Height` | ✅ | ✅ | |
| `BloodPressure` | ✅ | ✅ | |
| `BloodGlucose` | ✅ | ✅ | |
| `OxygenSaturation` | ✅ | ✅ | |
| `BodyTemperature` | ✅ | ✅ | |
| `BodyFat` | ✅ | ✅ | |
| `Hydration` | ✅ | ✅ | |
| `ExerciseSession` | ✅ | ✅ | |
| `RestingHeartRate` | ✅ | ✅ | |
| `RespiratoryRate` | ✅ | ✅ | |
| `FloorsClimbed` | ✅ | ✅ | |
| `ElevationGained` | ✅ | ✅ | |
| `MindfulnessSession` | ✅ | ✅ | Requires `getFeatureStatus('mindfulnessSession')` |
| `SkinTemperature` | ✅ | ✅ | Requires `getFeatureStatus('skinTemperature')` |
| `ActivityIntensity` | ✅ | ✅ | Requires `getFeatureStatus('activityIntensity')` |

### Feature-gated APIs

```ts
import {
getFeatureStatus,
checkIfMatchmakingIsPossible,
launchMatchmaking,
createMedicalDataSource,
upsertMedicalResources,
readMedicalResources,
MedicalResourceType,
} from '@solutionforest/android-health-connect';

// Feature availability (skin temperature, mindfulness, activity intensity, matchmaking, PHR, …)
const skinTemp = await getFeatureStatus('skinTemperature'); // 'available' | 'unavailable'

// Matchmaking (experimental) — discover apps/devices that can write data you can read
if ((await getFeatureStatus('matchmaking')) === 'available') {
const { isMatchmakingPossible } = await checkIfMatchmakingIsPossible({
recordTypes: ['Steps', 'HeartRate'],
});
if (isMatchmakingPossible) {
await launchMatchmaking({ recordTypes: ['Steps', 'HeartRate'] });
}
}

// Personal Health Record / medical (experimental) — FHIR MedicalDataSource + MedicalResource
if ((await getFeatureStatus('personalHealthRecord')) === 'available') {
const source = await createMedicalDataSource({
displayName: 'Clinic FHIR',
fhirBaseUri: 'https://example.com/fhir/',
fhirVersion: { major: 4, minor: 0, patch: 1 },
});
await upsertMedicalResources([
{
dataSourceId: source.id,
fhirVersion: source.fhirVersion,
data: JSON.stringify({ resourceType: 'AllergyIntolerance', id: '1', /* … */ }),
},
]);
const page = await readMedicalResources({
medicalResourceType: MedicalResourceType.ALLERGIES_INTOLERANCES,
medicalDataSourceIds: [source.id],
});
}
```

## Upgrade reminders

Expand Down Expand Up @@ -340,7 +390,21 @@ Maintainers: CI, CodeQL, Release, and the weekly version-check Action run on **G
| `deleteRecordsById(type, ids)` | `Promise<void>` | Delete by IDs |
| `readSteps(options?)` | `Promise<ReadRecordsResponse<StepsRecord>>` | Convenience helper |
| `readHeartRate(options?)` | … | Convenience helper |
| *(and one per record type)* | | |
| *(and one per record type, including Mindfulness / SkinTemperature / ActivityIntensity)* | | |

### Features / Matchmaking / PHR

| Function | Returns | Description |
|---|---|---|
| `getFeatureStatus(feature)` | `Promise<'available' \| 'unavailable'>` | Check HC feature flags |
| `checkIfMatchmakingIsPossible(opts?)` | `Promise<{ isMatchmakingPossible }>` | Whether Matchmaking UI has candidates |
| `launchMatchmaking(opts?)` | `Promise<boolean>` | Launch Matchmaking activity |
| `createMedicalDataSource(req)` | `Promise<MedicalDataSource>` | Create FHIR data source |
| `getMedicalDataSources(req?)` | `Promise<MedicalDataSource[]>` | List medical data sources |
| `deleteMedicalDataSourceWithData(id)` | `Promise<void>` | Delete source + its resources |
| `upsertMedicalResources(reqs)` | `Promise<MedicalResource[]>` | Insert/update FHIR resources |
| `readMedicalResources(req)` | `Promise<ReadMedicalResourcesResponse>` | Paged medical resource read |
| `deleteMedicalResources(req)` | `Promise<void>` | Delete by IDs or filters |

## Contributing

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,12 @@ import android.app.Activity
import android.content.Intent
import android.net.Uri
import android.util.Log
import androidx.health.connect.client.ExperimentalMatchmakingApi
import androidx.health.connect.client.HealthConnectClient
import androidx.health.connect.client.PermissionController
import androidx.health.connect.client.feature.ExperimentalPersonalHealthRecordApi
import androidx.health.connect.client.matchmaking.MatchmakingRequest
import androidx.health.connect.client.records.metadata.DataOrigin
import com.facebook.react.bridge.ActivityEventListener
import com.facebook.react.bridge.Arguments
import com.facebook.react.bridge.Promise
Expand All @@ -20,12 +24,14 @@ import org.json.JSONArray
import org.json.JSONObject
import java.time.Instant

@OptIn(ExperimentalMatchmakingApi::class, ExperimentalPersonalHealthRecordApi::class)
class AndroidHealthConnectModule(reactContext: ReactApplicationContext) :
NativeAndroidHealthConnectSpec(reactContext), ActivityEventListener {

companion object {
const val NAME = NativeAndroidHealthConnectSpec.NAME
private const val PERMISSION_REQUEST_CODE = 21432
private const val MATCHMAKING_REQUEST_CODE = 21433
private const val TAG = "AndroidHealthConnect"
private const val HC_PACKAGE = "com.google.android.apps.healthdata"
private const val HC_PLAY_STORE_URI =
Expand All @@ -47,6 +53,10 @@ class AndroidHealthConnectModule(reactContext: ReactApplicationContext) :
@Volatile
private var pendingPermissionPromise: Promise? = null

/** Pending promise for an in-flight matchmaking flow. */
@Volatile
private var pendingMatchmakingPromise: Promise? = null

init {
reactContext.addActivityEventListener(this)
}
Expand Down Expand Up @@ -215,6 +225,150 @@ class AndroidHealthConnectModule(reactContext: ReactApplicationContext) :
}
}

// ─── Feature availability ─────────────────────────────────────────────────

override fun getFeatureStatus(feature: String, promise: Promise) {
if (!isAvailable(promise)) return
moduleScope.launch {
try {
promise.resolve(FeatureSupport.getStatus(healthConnectClient, feature))
} catch (e: Exception) {
promise.reject("FEATURE_STATUS_ERROR", e.message, e)
}
}
}

// ─── Matchmaking ──────────────────────────────────────────────────────────

override fun checkIfMatchmakingIsPossible(options: String, promise: Promise) {
if (!isAvailable(promise)) return
moduleScope.launch {
try {
val request = parseMatchmakingRequest(JSONObject(options))
val response = healthConnectClient.checkIfMatchmakingIsPossible(request)
promise.resolve(
JSONObject().put("isMatchmakingPossible", response.isMatchmakingPossible).toString()
)
} catch (e: Exception) {
Log.e(TAG, "checkIfMatchmakingIsPossible error", e)
promise.reject("MATCHMAKING_ERROR", e.message, e)
}
}
}

override fun launchMatchmaking(options: String, promise: Promise) {
val activity = reactApplicationContext.currentActivity
if (activity == null) {
promise.reject("NO_ACTIVITY", "No foreground Activity available")
return
}
if (!isAvailable(promise)) return
moduleScope.launch {
try {
val request = parseMatchmakingRequest(JSONObject(options))
val intent = healthConnectClient.createMatchmakingIntent(request)
pendingMatchmakingPromise = promise
activity.runOnUiThread {
activity.startActivityForResult(intent, MATCHMAKING_REQUEST_CODE)
}
} catch (e: Exception) {
Log.e(TAG, "launchMatchmaking error", e)
promise.reject("MATCHMAKING_ERROR", e.message, e)
}
}
}

// ─── Personal Health Record ───────────────────────────────────────────────

override fun createMedicalDataSource(request: String, promise: Promise) {
if (!isAvailable(promise)) return
moduleScope.launch {
try {
val source = healthConnectClient.createMedicalDataSource(
PhrMapper.createRequestFromJson(JSONObject(request))
)
promise.resolve(PhrMapper.medicalDataSourceToJson(source).toString())
} catch (e: Exception) {
Log.e(TAG, "createMedicalDataSource error", e)
promise.reject("PHR_ERROR", e.message, e)
}
}
}

override fun deleteMedicalDataSourceWithData(id: String, promise: Promise) {
if (!isAvailable(promise)) return
moduleScope.launch {
try {
healthConnectClient.deleteMedicalDataSourceWithData(id)
promise.resolve(true)
} catch (e: Exception) {
Log.e(TAG, "deleteMedicalDataSourceWithData error", e)
promise.reject("PHR_ERROR", e.message, e)
}
}
}

override fun getMedicalDataSources(request: String, promise: Promise) {
if (!isAvailable(promise)) return
moduleScope.launch {
try {
val result = PhrMapper.getMedicalDataSources(
healthConnectClient, JSONObject(request.ifEmpty { "{}" })
)
promise.resolve(result.toString())
} catch (e: Exception) {
Log.e(TAG, "getMedicalDataSources error", e)
promise.reject("PHR_ERROR", e.message, e)
}
}
}

override fun upsertMedicalResources(requests: String, promise: Promise) {
if (!isAvailable(promise)) return
moduleScope.launch {
try {
val upserted = healthConnectClient.upsertMedicalResources(
PhrMapper.upsertRequestsFromJson(JSONArray(requests))
)
val arr = JSONArray().apply {
upserted.forEach { put(PhrMapper.medicalResourceToJson(it)) }
}
promise.resolve(arr.toString())
} catch (e: Exception) {
Log.e(TAG, "upsertMedicalResources error", e)
promise.reject("PHR_ERROR", e.message, e)
}
}
}

override fun readMedicalResources(request: String, promise: Promise) {
if (!isAvailable(promise)) return
moduleScope.launch {
try {
val result = PhrMapper.readMedicalResources(
healthConnectClient, JSONObject(request)
)
promise.resolve(result.toString())
} catch (e: Exception) {
Log.e(TAG, "readMedicalResources error", e)
promise.reject("PHR_ERROR", e.message, e)
}
}
}

override fun deleteMedicalResources(request: String, promise: Promise) {
if (!isAvailable(promise)) return
moduleScope.launch {
try {
PhrMapper.deleteMedicalResources(healthConnectClient, JSONObject(request))
promise.resolve(true)
} catch (e: Exception) {
Log.e(TAG, "deleteMedicalResources error", e)
promise.reject("PHR_ERROR", e.message, e)
}
}
}

// ─── ActivityEventListener ────────────────────────────────────────────────

override fun onActivityResult(
Expand All @@ -223,12 +377,19 @@ class AndroidHealthConnectModule(reactContext: ReactApplicationContext) :
resultCode: Int,
data: Intent?,
) {
if (requestCode != PERMISSION_REQUEST_CODE) return
val granted = requestPermissionsContract.parseResult(resultCode, data)
val array = Arguments.createArray()
granted.forEach { array.pushString(it) }
pendingPermissionPromise?.resolve(array)
pendingPermissionPromise = null
when (requestCode) {
PERMISSION_REQUEST_CODE -> {
val granted = requestPermissionsContract.parseResult(resultCode, data)
val array = Arguments.createArray()
granted.forEach { array.pushString(it) }
pendingPermissionPromise?.resolve(array)
pendingPermissionPromise = null
}
MATCHMAKING_REQUEST_CODE -> {
pendingMatchmakingPromise?.resolve(resultCode == Activity.RESULT_OK)
pendingMatchmakingPromise = null
}
}
}

override fun onNewIntent(intent: Intent) {}
Expand Down Expand Up @@ -265,4 +426,28 @@ class AndroidHealthConnectModule(reactContext: ReactApplicationContext) :
Log.e(TAG, "Could not start activity: ${e.message}")
}
}

private fun parseMatchmakingRequest(options: JSONObject): MatchmakingRequest {
val recordTypesArr = options.optJSONArray("recordTypes")
val recordTypes =
if (recordTypesArr != null) {
(0 until recordTypesArr.length())
.map { FeatureSupport.recordClassForType(recordTypesArr.getString(it)) }
.toSet()
} else {
emptySet()
}
val included = parseDataOrigins(options.optJSONArray("includedDataSources"))
val excluded = parseDataOrigins(options.optJSONArray("excludedDataSources"))
return MatchmakingRequest(
recordTypes = recordTypes,
includedDataSources = included,
excludedDataSources = excluded,
)
}

private fun parseDataOrigins(arr: JSONArray?): Set<DataOrigin> {
if (arr == null) return emptySet()
return (0 until arr.length()).map { DataOrigin(arr.getString(it)) }.toSet()
}
}
Loading
Loading