Skip to content
Open
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
2 changes: 2 additions & 0 deletions gradle/libs.versions.toml
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@ google-maps = "20.0.0"
gradle-versions = "0.53.0"
guava = "33.5.0-jre"
guava-android = "33.5.0-jre"
health-connect = "1.1.0-alpha11"
hilt = "2.59.2"
horologist = "0.8.3-alpha"
junit = "4.13.2"
Expand Down Expand Up @@ -182,6 +183,7 @@ androidx-glance-appwidget-testing = { module = "androidx.glance:glance-appwidget
androidx-glance-material3 = { module = "androidx.glance:glance-material3", version.ref = "androidx-glance-appwidget" }
androidx-glance-testing = { module = "androidx.glance:glance-testing", version.ref = "androidx-glance-appwidget" }
androidx-graphics-shapes = "androidx.graphics:graphics-shapes:1.1.0"
androidx-health-connect = { group = "androidx.health.connect", name = "connect-client", version.ref = "health-connect" }
androidx-hilt-navigation-compose = { module = "androidx.hilt:hilt-navigation-compose", version.ref = "androidxHiltNavigationCompose" }
androidx-lifecycle-runtime = { module = "androidx.lifecycle:lifecycle-runtime-ktx", version.ref = "androidx-lifecycle-runtime-compose" }
androidx-lifecycle-runtime-compose = { module = "androidx.lifecycle:lifecycle-runtime-compose", version.ref = "androidx-lifecycle-runtime-compose" }
Expand Down
1 change: 1 addition & 0 deletions healthconnect/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
/build
52 changes: 52 additions & 0 deletions healthconnect/build.gradle.kts
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
plugins {
alias(libs.plugins.android.application)
alias(libs.plugins.compose.compiler)
}

android {
namespace = "com.example.healthconnect"
compileSdkPreview = "CinnamonBun"

defaultConfig {
applicationId = "com.example.healthconnect"
minSdk = 26
targetSdk = 36
versionCode = 1
versionName = "1.0"

testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
}

buildTypes {
release {
isMinifyEnabled = false
proguardFiles(
getDefaultProguardFile("proguard-android-optimize.txt"),
"proguard-rules.pro"
)
}
}
compileOptions {
sourceCompatibility = JavaVersion.VERSION_11
targetCompatibility = JavaVersion.VERSION_11
}
buildFeatures {
compose = true
}
}

dependencies {
implementation(libs.androidx.core.ktx)
implementation(libs.androidx.lifecycle.runtime)
implementation(libs.androidx.activity.compose)
implementation(platform(libs.androidx.compose.bom))
implementation(libs.androidx.compose.ui)
implementation(libs.androidx.compose.ui.graphics)
implementation(libs.androidx.compose.ui.tooling.preview)
implementation(libs.androidx.compose.material3)
implementation(libs.androidx.health.connect)
implementation(libs.androidx.work.runtime.ktx)

debugImplementation(libs.androidx.compose.ui.tooling)
debugImplementation(libs.androidx.compose.ui.test.manifest)
}
21 changes: 21 additions & 0 deletions healthconnect/proguard-rules.pro
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
# Add project specific ProGuard rules here.
# You can control the set of applied configuration files using the
# proguardFiles setting in build.gradle.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html

# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
# public *;
#}

# Uncomment this to preserve the line number information for
# debugging stack traces.
#-keepattributes SourceFile,LineNumberTable

# If you keep the line number information, uncomment this to
# hide the original source file name.
#-renamesourcefileattribute SourceFile
30 changes: 30 additions & 0 deletions healthconnect/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">

<queries>
<package android:name="com.google.android.apps.healthdata" />
</queries>

<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.Snippets">

<activity
android:name=".HealthConnectActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>

<intent-filter>
<action android:name="androidx.health.ACTION_SHOW_PERMISSIONS_RATIONALE" />
</intent-filter>
</activity>

</application>
</manifest>
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
package com.example.healthconnect

import androidx.health.connect.client.HealthConnectClient
import androidx.health.connect.client.changes.DeletionChange
import androidx.health.connect.client.changes.UpsertionChange
import androidx.health.connect.client.request.ChangesTokenRequest
import androidx.health.connect.client.records.WeightRecord
import android.content.Context

class ChangesManager(private val healthConnectClient: HealthConnectClient) {

suspend fun getChangesToken(): String {
// [START android_healthconnect_get_changes_token]
val changesToken = healthConnectClient.getChangesToken(
ChangesTokenRequest(recordTypes = setOf(WeightRecord::class))
)
// [END android_healthconnect_get_changes_token]
return changesToken
}

// [START android_healthconnect_process_changes]
suspend fun processChanges(token: String): String {
var nextChangesToken = token
do {
val response = healthConnectClient.getChanges(nextChangesToken)
response.changes.forEach { change ->
when (change) {
is UpsertionChange -> { /* Process Upsert */ }
is DeletionChange -> { /* Process Deletion */ }
}
}
nextChangesToken = response.nextChangesToken
} while (response.hasMore)
return nextChangesToken
}
// [END android_healthconnect_process_changes]
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,139 @@
/*
* Copyright 2026 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*/

package com.example.healthconnect

import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.material3.Button
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.SnackbarHost
import androidx.compose.material3.SnackbarHostState
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.health.connect.client.HealthConnectClient
import com.example.healthconnect.ui.theme.SnippetsTheme
import kotlinx.coroutines.launch
import java.time.Clock
Comment thread
shounbi marked this conversation as resolved.
import java.time.Instant
import java.time.Duration

class HealthConnectActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enableEdgeToEdge()

setContent {
SnippetsTheme {
HealthConnectScreen(Modifier.fillMaxSize())
}
}
}
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun HealthConnectScreen(modifier: Modifier) {
val context = LocalContext.current
val coroutineScope = rememberCoroutineScope()
val snackbarHostState = remember { SnackbarHostState() }

// [START android_healthconnect_get_client]
val availabilityStatus = HealthConnectClient.getSdkStatus(context)
if (availabilityStatus == HealthConnectClient.SDK_UNAVAILABLE) {
Box(modifier = modifier.padding(16.dp), contentAlignment = Alignment.Center) {
Text(
text = "Health Connect is not available on this device. Please ensure it is installed and updated.",
style = MaterialTheme.typography.bodyLarge,
textAlign = TextAlign.Center
)
}
return
}
Comment thread
shounbi marked this conversation as resolved.

val healthConnectClient = remember {
if (availabilityStatus == HealthConnectClient.SDK_AVAILABLE) {
HealthConnectClient.getOrCreate(context)
} else {
null
}
}
// [END android_healthconnect_get_client]

// Initialize our snippet manager
val manager = remember(healthConnectClient) {
healthConnectClient?.let { HealthConnectManager(it) }
}

Scaffold(
modifier = modifier,
snackbarHost = { SnackbarHost(snackbarHostState) },
topBar = { TopAppBar(title = { Text("Health Connect Snippets") }) },
) { innerPadding ->
LazyColumn(Modifier.padding(innerPadding).padding(horizontal = 16.dp)) {
item {
Text(
text = if (healthConnectClient != null)
"Health Connect is available"
else
"Health Connect is not available",
modifier = Modifier.padding(vertical = 16.dp)
)
}

if (manager != null) {
item {
Button(onClick = {
coroutineScope.launch {
val startTime = Instant.now().minusSeconds(3600)
val endTime = Instant.now()
manager.insertSteps(startTime, endTime)
snackbarHostState.showSnackbar("Steps inserted!")
}
}) {
Text("Run: Insert Steps")
}
}

item {
Button(
modifier = Modifier.padding(top = 8.dp),
onClick = {
coroutineScope.launch {
val startTime = Instant.now().minus(Duration.ofDays(1))
val endTime = Instant.now()

val total = manager.readStepsAggregate(startTime, endTime)
snackbarHostState.showSnackbar("Total Steps: $total")
}
}) {
Text("Run: Read Steps Aggregate")
}
}
}
}
}
}
Loading