### Start Running Exercise with ExerciseClient Source: https://developer.samsung.com/health/sensor/sample/sweat-loss-monitor/implementation.html Configures an exercise session for running using ExerciseConfig and initiates it via the ExerciseClient. It includes error handling through FutureCallback to manage the asynchronous start process. ```java protected void startExercise() throws RuntimeException { final ExerciseConfig.Builder exerciseConfigBuilder = ExerciseConfig.builder(ExerciseType.RUNNING) .setDataTypes(new HashSet<>(Arrays.asList(DataType.DISTANCE, STEPS_PER_MINUTE))) .setIsAutoPauseAndResumeEnabled(false) .setIsGpsEnabled(false); Log.i(TAG, "Calling startExerciseAsync"); Futures.addCallback(exerciseClient.startExerciseAsync(exerciseConfigBuilder.build()), new FutureCallback() { @Override public void onSuccess(@Nullable Void result) { Log.i(TAG, "startExerciseAsync: onSuccess()."); } @Override public void onFailure(@NonNull Throwable t) { Log.i(TAG, "startExerciseAsync onFailure() starting exercise : " + t.getMessage()); healthServicesEventListener.onExerciseError(R.string.exercise_starting_error); } }, Executors.newSingleThreadExecutor()); } ``` -------------------------------- ### Initialize Development Environment with Yarn Source: https://developer.samsung.com/health/research/developer-guide/installation/install-portal.html Commands to enable the Yarn package manager, install project dependencies, and launch the development server for local source code modification. ```shell corepack enable yarn yarn dev ``` -------------------------------- ### User List JSON Example Source: https://developer.samsung.com/health/stack/developer-guide/portal-REST-API-reference/all-endpoints/account-service-api-endpoints.html An example of a JSON array representing a list of users. Each user object contains email, ID, roles, and profile information. ```json [ { "email": "cubist@samsung.com", "id": "7d08351b-85b6-488e-a8a2-b8653defb865", "roles": [ "project_sample:research-assistant" ], "profile": { "name": "david.lee", "status": "active" } } ] ``` -------------------------------- ### Get Start Local Date Time - Kotlin Source: https://developer.samsung.com/health/data/api-reference/-shd/com.samsung.android.sdk.health.data.data/-aggregated-data/get-start-local-date-time.html Retrieves the start time of the data as a LocalDateTime. The start time is inclusive and based on the zone offset, represented in milliseconds. This function is available since version 1.0.0. ```kotlin fun getStartLocalDateTime(): LocalDateTime { // Implementation to retrieve start time // ... return LocalDateTime.now() // Placeholder } ``` -------------------------------- ### Instantiate and Start OnboardingTask Source: https://developer.samsung.com/health/research/developer-guide/SDK-Documentation/tutorials/healthstack-kit-tutorial-creating-custom-task.html Demonstrates how to create an instance of the `OnboardingTask` and initiate its execution. This code snippet shows the practical application of the defined task, making it ready for user interaction. ```kotlin val onboardingTask = OnboardingTask( id = "onboarding_task", name = "Onboarding Task", description = "A simple onboarding task with two steps" ) // Start the onboarding task by rendering the first step onboardingTask.start() ``` -------------------------------- ### Configure Exercise and Retrieve Capabilities Source: https://developer.samsung.com/health/blog/en/2022/02/16/tracking-exercises-with-galaxy-watch Demonstrates how to initialize an ExerciseClient, define an exercise type, and query supported data types using ListenableFuture and FutureCallback. ```Java ExerciseClient exerciseClient = client.getExerciseClient(); ExerciseType exerciseType = ExerciseType.DEADLIFT; ExerciseConfigBuilder exerciseConfigBuilder = ExerciseConfig.builder() .setExerciseType(exerciseType); ListenableFuture capabilitiesListenableFuture = exerciseClient.getCapabilities(); new FutureCallback() { @Override public void onSuccess(@Nullable ExerciseCapabilities result) { ExerciseTypeCapabilities exerciseTypeCapabilities = result.getExerciseTypeCapabilities(exerciseType); Set exerciseCapabilitiesSet = exerciseTypeCapabilities.getExerciseCapabilities(result); } }; exerciseConfigBuilder = ExerciseConfig.builder() .setExerciseType(exerciseType) .setDataTypes(exerciseCapabilitiesSet); ``` -------------------------------- ### Get Start Local Date Time (Kotlin) Source: https://developer.samsung.com/health/data/api-reference/-shd/com.samsung.android.sdk.health.data.data/-health-data-point/index.html Retrieves the start time of the data as a LocalDateTime object. This function is essential for time-series data analysis within the Samsung Health platform. ```kotlin fun getStartLocalDateTime(): LocalDateTime ``` -------------------------------- ### GET /health/blood-glucose Source: https://developer.samsung.com/health/android/migration-guide/overview.html Retrieves blood glucose measurements for a specific time range. ```APIDOC ## GET /health/blood-glucose ### Description Reads blood glucose data records from the Samsung Health store for a defined time interval. ### Method GET ### Endpoint /health/blood-glucose ### Parameters #### Query Parameters - **startTime** (Long) - Required - Start of the retrieval window. - **endTime** (Long) - Required - End of the retrieval window. ### Response #### Success Response (200) - **glucose** (Float) - Blood glucose level. - **mealType** (Integer) - Type of meal associated with the reading. - **measurementType** (Integer) - Method of measurement. #### Response Example { "data": [ { "glucose": 95.0, "mealType": 1, "measurementType": 2 } ] } ``` -------------------------------- ### Create Step Classes for Onboarding Source: https://developer.samsung.com/health/research/developer-guide/SDK-Documentation/tutorials/healthstack-kit-tutorial-creating-custom-task.html Defines `WelcomeStep` and `ProfileInfoStep` classes that extend the base `Step` class. These classes are essential components of the onboarding task, each representing a distinct stage in the user's onboarding journey. ```kotlin import healthstack.kit.task.base.Step class WelcomeStep : Step( id = "welcome", name = "Welcome", model = WelcomeStepModel(), view = WelcomeView() ) { override fun getResult(): Unit = Unit } class ProfileInfoStep : Step( id = "profile_info", name = "Profile Information", model = ProfileInfoStepModel(), view = ProfileInfoView() ) { override fun getResult(): Unit = Unit } ``` -------------------------------- ### GET /user-profile Source: https://developer.samsung.com/health/android/migration-guide/overview.html Retrieves the user's profile information including gender, height, and weight. ```APIDOC ## GET /user-profile ### Description Fetches the user profile data from the Samsung Health SDK. ### Method GET ### Endpoint HealthUserProfile ### Parameters None ### Response #### Success Response (200) - **gender** (String) - User gender (MALE, FEMALE, UNKNOWN). - **height** (Float) - User height in cm. - **weight** (Float) - User weight in kg. #### Response Example { "gender": "MALE", "height": 180.0, "weight": 75.0 } ``` -------------------------------- ### Add Steps to OrderedTask Source: https://developer.samsung.com/health/research/developer-guide/SDK-Documentation/tutorials/healthstack-kit-tutorial-creating-custom-task.html Implements the `OnboardingTask` class, inheriting from `OrderedTask`. This class aggregates the previously defined `WelcomeStep` and `ProfileInfoStep`, establishing the sequence for the onboarding process. ```kotlin import healthstack.kit.task.base.OrderedTask import healthstack.kit.task.base.Step class OnboardingTask( id: String, name: String, description: String ) : OrderedTask (id, name, description) { init { steps.add(WelcomeStep()) steps.add(ProfileInfoStep()) } } ``` -------------------------------- ### GET /body-temperature Source: https://developer.samsung.com/health/android/migration-guide/overview.html Retrieves body temperature data points for the current day using the HealthDataStore. ```APIDOC ## GET /body-temperature ### Description Reads body temperature data from the Samsung Health Data SDK for the current day. ### Method GET ### Endpoint DataTypes.BODY_TEMPERATURE ### Parameters #### Query Parameters - **startTime** (LocalDateTime) - Required - Start of the time range. - **endTime** (LocalDateTime) - Required - End of the time range. ### Request Example N/A (SDK Method Call) ### Response #### Success Response (200) - **dataList** (List) - List of body temperature data points. - **bodyTemperature** (Float) - The recorded temperature value. #### Response Example { "bodyTemperature": 37.0 } ``` -------------------------------- ### Get Start Time of Today for Health Data Reading Source: https://developer.samsung.com/health/android/data/api-reference/com/samsung/android/sdk/healthdata/HealthDataResolver.ReadRequest.html This Java function calculates the start time of the current day in UTC, which is used to define the time range for reading health data. It sets the hour, minute, second, and millisecond to zero. ```java private long getStartTimeOfToday() { Calendar today = Calendar.getInstance(TimeZone.getTimeZone("UTC")); today.set(Calendar.HOUR_OF_DAY, 0); today.set(Calendar.MINUTE, 0); today.set(Calendar.SECOND, 0); today.set(Calendar.MILLISECOND, 0); return today.getTimeInMillis(); } ``` -------------------------------- ### Write Heart Rate Data Source: https://developer.samsung.com/health/android/migration-guide/overview.html This section provides an example of how to write heart rate data using the Samsung Health SDK for Android. ```APIDOC ## Write Heart Rate Data ### Description This endpoint demonstrates writing heart rate data using the Samsung Health SDK for Android. ### Method N/A (This is a code example for an Android SDK function) ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example ```kotlin // Example code for writing heart rate data would go here. // Please refer to the Samsung Health SDK documentation for specific implementation details. ``` ### Response #### Success Response (200) N/A (This is a code example for an Android SDK function) #### Response Example N/A ``` -------------------------------- ### Prepare Exercise Logs with ExerciseLog Source: https://developer.samsung.com/health/android/migration-guide/exercise-app-example.html Demonstrates how to create a list of ExerciseLog objects to capture phase-specific exercise data like heart rate and speed. This approach avoids manual JSON serialization. ```kotlin val exerciseLog = listOf( ExerciseLog.of( timestamp = Instant.ofEpochSecond(1766394000), heartRate = 144f, speed = 1.6f, cadence = null, count = null, power = null ), ExerciseLog.of( timestamp = Instant.ofEpochSecond(1766394030), heartRate = 146f, speed = 1.8f, cadence = null, count = null, power = null ) ) ``` -------------------------------- ### Get Sleep Data Source Device Info with Samsung Health Data SDK Source: https://developer.samsung.com/health/android/migration-guide/overview.html Retrieves source device information for sleep data using the Samsung Health Data SDK. It queries sleep data and uses the device manager to get details about the device that provided the data. ```kotlin suspend fun getSourceDeviceInfoOfSleepData( healthDataStore: HealthDataStore ) { val resultCount = 1 val readRequest = DataTypes.SLEEP.readDataRequestBuilder .setOrdering(Ordering.DESC) .setLimit(resultCount) .build() try { val result = healthDataStore.readData(readRequest) result.dataList.forEach { sleepData -> val deviceManager = healthDataStore.getDeviceManager() sleepData.dataSource?.let { dataSource -> val device = deviceManager.getDevice(dataSource.deviceId) val deviceId = device?.id val deviceName = device?.name val deviceType = device?.deviceType } } } catch (e: Exception) { e.printStackTrace() } } ``` -------------------------------- ### Compile Backend Microservices (Gradle - Mac/Linux) Source: https://developer.samsung.com/health/stack/developer-guide/installation/install-backend.html This snippet provides the Gradle commands to clean and build the backend-related microservices on Mac and Linux systems. The '-x detekt' flag excludes the detekt static analysis tool from the build process. ```gradle ./gradlew clean ./gradlew build -x detekt ``` -------------------------------- ### Initialize and Get Tracking Capability Source: https://developer.samsung.com/health/sensor/api-reference/com/samsung/android/service/health/tracking/HealthTrackingService.html Demonstrates initializing the HealthTrackingService and then retrieving its tracking capabilities. This is a common pattern for starting to use the health tracking features. ```java HealthTrackingService healthTrackingService = new HealthTrackingService(connectionListener, context); HealthTrackerCapability healthTrackerCapability = healthTrackingService.getTrackingCapability(); ``` -------------------------------- ### Initialize Firebase Service Account File Source: https://developer.samsung.com/health/research/developer-guide/installation/install-backend.md Commands to navigate to the platform directory and create a placeholder file for the Firebase service account credentials. ```bash cd backend-system/platform touch service-account-key.json ``` -------------------------------- ### Writing Blood Pressure Data (Data SDK) Source: https://developer.samsung.com/health/android/migration-guide/overview.html Example code for writing blood pressure data using the Samsung Health Data SDK. ```APIDOC ## POST /healthdata/bloodpressure ### Description This endpoint allows you to write blood pressure data to Samsung Health using the Samsung Health Data SDK. ### Method POST ### Endpoint /healthdata/bloodpressure ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **healthDataStore** (HealthDataStore) - Required - The HealthDataStore instance. - **systolic** (Float) - Required - Systolic blood pressure value. - **diastolic** (Float) - Required - Diastolic blood pressure value. - **mean** (Float) - Optional - Mean blood pressure value. ### Request Example ```kotlin suspend fun insertBloodPressureData(healthDataStore: HealthDataStore) { val startTime = LocalDateTime.now().minusMinutes(10) val systolic = 119f val diastolic = 87f val mean = 0f try { val healthDataPoint = HealthDataPoint.builder() .setLocalStartTime(startTime) .addFieldData(DataType.BloodPressureType.SYSTOLIC, systolic) .addFieldData(DataType.BloodPressureType.DIASTOLIC, diastolic) .addFieldData(DataType.BloodPressureType.MEAN, mean) .build() val insertDataRequest = DataTypes.BLOOD_PRESSURE.insertDataRequestBuilder .addData(healthDataPoint) .build() healthDataStore.insertData(insertDataRequest) } catch (e: Exception) { e.printStackTrace() } } ``` ### Response #### Success Response (200) Indicates successful insertion of blood pressure data. #### Response Example (No specific response body is detailed for success, operation is confirmed by lack of errors.) ``` -------------------------------- ### Initialize HealthStackBackendAdapter Source: https://developer.samsung.com/health/research/developer-guide/SDK-Documentation/references/backend-integration/healthstack-adapter/healthstack.backend.integration.adapter/-health-stack-backend-adapter/index.html Demonstrates the constructor initialization for the HealthStackBackendAdapter, which requires a network client and a project identifier to facilitate backend communication. ```kotlin class HealthStackBackendAdapter(networkClient: HealthStackBackendAPI, projectId: String) : BackendFacade ``` -------------------------------- ### Build and Deploy Production Portal with Docker Source: https://developer.samsung.com/health/research/developer-guide/installation/install-portal.html Commands to clone the repository, build a containerized production image with specific API configurations, and execute the container. ```shell git clone https://github.com/S-HealthStack/web-portal.git cd web-portal docker build . -t open-source-portal \ --build-arg API_URL="http://localhost:8080" \ --build-arg PUBLIC_PATH='/' \ --build-arg MOCK_API='/api' docker run -d -p 8081:80 open-source-portal ``` -------------------------------- ### Writing Blood Pressure Data (Android SDK) Source: https://developer.samsung.com/health/android/migration-guide/overview.html Example code for writing blood pressure data using the Samsung Health SDK for Android. ```APIDOC ## POST /healthdata/bloodpressure ### Description This endpoint allows you to write blood pressure data to Samsung Health using the Android SDK. ### Method POST ### Endpoint /healthdata/bloodpressure ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **healthDataStore** (HealthDataStore) - Required - The HealthDataStore instance. - **systolic** (Float) - Required - Systolic blood pressure value. - **diastolic** (Float) - Required - Diastolic blood pressure value. - **mean** (Float) - Optional - Mean blood pressure value. ### Request Example ```kotlin fun insertBloodPressureData(healthDataStore: HealthDataStore) { val handler = Handler(Looper.getMainLooper()) val healthDataResolver = HealthDataResolver(healthDataStore, handler) val healthDeviceManager = HealthDeviceManager(healthDataStore) val tenMinutesAsSeconds = 600L val startTime = Instant.now().minusSeconds(tenMinutesAsSeconds) val timeOffset = TimeZone.getDefault().getOffset(startTime.toEpochMilli()) val systolic = 119f val diastolic = 87f val mean = 0f val bloodPressureData = HealthData().apply { sourceDevice = healthDeviceManager.localDevice.uuid putLong(HealthConstants.BloodPressure.START_TIME, startTime.toEpochMilli()) putLong(HealthConstants.BloodPressure.TIME_OFFSET, timeOffset.toLong()) putFloat(HealthConstants.BloodPressure.SYSTOLIC, systolic) putFloat(HealthConstants.BloodPressure.DIASTOLIC, diastolic) putFloat(HealthConstants.BloodPressure.MEAN, mean) } val insertRequest = InsertRequest.Builder() .setDataType(HealthConstants.BloodPressure.HEALTH_DATA_TYPE) .build() insertRequest.addHealthData(bloodPressureData) try { val insertResult = healthDataResolver.insert(insertRequest).await() if (insertResult.status != BaseResult.STATUS_SUCCESSFUL) { Log.i( MainActivity.APP_TAG, "Error inserting blood pressure data. Error code: ${insertResult.status}" ) } } catch (e: Exception) { e.printStackTrace() } } ``` ### Response #### Success Response (200) Indicates successful insertion of blood pressure data. #### Response Example (No specific response body is detailed for success, operation is confirmed by lack of errors.) ``` -------------------------------- ### Build Static Production Files Source: https://developer.samsung.com/health/research/developer-guide/installation/install-portal.html Alternative method to build static assets for hosting on a standard web server instead of using Docker. ```shell corepack enable yarn API_URL=https://example.com yarn build ``` -------------------------------- ### Samsung Health SDK for Android: Aggregate Request Example Source: https://developer.samsung.com/health/android/migration-guide/exercise-app-example.html This snippet demonstrates how to create an AggregateRequest to read the total exercise calories burned since the start of the day using the Samsung Health SDK for Android. ```APIDOC ## POST /samsung-health/sdk/android/aggregate ### Description Creates an `AggregateRequest` to fetch aggregated health data, specifically total exercise calories burned since the start of the day. ### Method POST ### Endpoint /samsung-health/sdk/android/aggregate ### Parameters #### Query Parameters - **startTime** (LocalDateTime) - Required - The start of the time range for aggregation. - **endTime** (LocalDateTime) - Required - The end of the time range for aggregation. #### Request Body This endpoint does not require a request body. The parameters are passed via query parameters. ### Request Example ```java // Assume startTime and endTime are defined LocalDateTime objects val exerciseTotalCaloriesId = "exercise_total_calories" val aggregateRequest = HealthDataResolver.AggregateRequest.Builder() .addFunction( HealthDataResolver.AggregateRequest.AggregateFunction.SUM, HealthConstants.Exercise.CALORIE, exerciseTotalCaloriesId ) .setLocalTimeRange( HealthConstants.Exercise.START_TIME, HealthConstants.Exercise.TIME_OFFSET, startTime, endTime ) .setDataType(HealthConstants.Exercise.HEALTH_DATA_TYPE) .build() // To retrieve the data: var totalCalories = 0 try { healthDataResolver.aggregate(aggregateRequest).await().run { try { val iterator = iterator() if (iterator.hasNext()) { val healthData = iterator.next() totalCalories = healthData.getInt(exerciseTotalCaloriesId) } } finally { close() } } } catch (exception: Exception) { exception.message?.let { Log.i(TAG, it) } } ``` ### Response #### Success Response (200) - **totalCalories** (Integer) - The total calories burned within the specified time range. #### Response Example ```json { "totalCalories": 500 } ``` ### Notes To get the total exercise duration, modify the `addFunction` call to use `HealthConstants.Exercise.DURATION` and a different key ID (e.g., "exercise_total_duration"). ``` -------------------------------- ### Android JVM: Get Next Breathing State Source: https://developer.samsung.com/health/research/developer-guide/SDK-Documentation/references/kit/healthstack.kit.task.activity.model/-guided-breathing-measure-model/-breathing-state/-companion/get-next.html Retrieves the next breathing state in a guided breathing exercise. This function is part of the HealthKit SDK and is used to manage the flow of breathing exercises. ```kotlin fun getNext(current: GuidedBreathingMeasureModel.BreathingState): GuidedBreathingMeasureModel.BreathingState ``` -------------------------------- ### Initialize and Use HealthPlatformAdapter Source: https://developer.samsung.com/health/research/developer-guide/SDK-Documentation/references/healthdata-link/healthplatform/healthstack.healthdata.link.healthplatform/-health-platform-adapter/index.html Demonstrates the class definition for HealthPlatformAdapter and provides examples of key asynchronous methods for data retrieval and permission handling. ```kotlin class HealthPlatformAdapter(healthDataClient: HealthDataClient, healthDataTypeNames: List) : HealthDataLink { // Example of retrieving health data within a time range suspend fun fetchHealthData(startTime: Instant, endTime: Instant, type: String): HealthData { return getHealthData(startTime, endTime, type) } // Example of checking permissions suspend fun checkAccess(): Boolean { return hasAllPermissions() } } ``` -------------------------------- ### Reading Body Temperature Data (Android SDK) Source: https://developer.samsung.com/health/android/migration-guide/overview.html Example code for reading today's body temperature data using the Samsung Health SDK for Android. ```APIDOC ## GET /healthdata/bodytemperature/today ### Description This endpoint allows you to read today's body temperature data recorded in Samsung Health using the Android SDK. ### Method GET ### Endpoint /healthdata/bodytemperature/today ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **healthDataStore** (HealthDataStore) - Required - The HealthDataStore instance. ### Request Example ```kotlin fun readTodayBodyTemperature( healthDataStore: HealthDataStore ) { val startTime = LocalDate.now().atStartOfDay().toInstant(ZoneOffset.UTC).toEpochMilli() val endTime = LocalDateTime.now().toInstant(ZoneOffset.UTC).toEpochMilli() val handler = Handler(Looper.getMainLooper()) val healthDataResolver = HealthDataResolver(healthDataStore, handler) val readRequest: HealthDataResolver.ReadRequest = HealthDataResolver.ReadRequest.Builder() .setDataType(HealthConstants.BodyTemperature.HEALTH_DATA_TYPE) .setLocalTimeRange( HealthConstants.BodyTemperature.START_TIME, HealthConstants.BodyTemperature.TIME_OFFSET, startTime, endTime ).build() try { healthDataResolver.read(readRequest).setResultListener { result -> try { result.lastOrNull()?.let { healthData -> val measurementStartTime = Date(healthData.getLong(HealthConstants.BodyTemperature.START_TIME)) val bodyTemperature = healthData.getFloat(HealthConstants.BodyTemperature.TEMPERATURE) } } finally { result.close() } } } catch (e: Exception) { e.printStackTrace() } } ``` ### Response #### Success Response (200) - **measurementStartTime** (Date) - The start time of the body temperature measurement. - **bodyTemperature** (Float) - The recorded body temperature value. #### Response Example ```json { "measurementStartTime": "2023-10-27T10:00:00.000Z", "bodyTemperature": 36.5 } ``` ``` -------------------------------- ### Compile Backend Microservices Source: https://developer.samsung.com/health/research/developer-guide/installation/install-backend.md Gradle commands to clean and build the backend microservices, excluding static analysis checks like detekt. ```bash cd backend-system ./gradlew clean ./gradlew build -x detekt ``` -------------------------------- ### Manage Exercise Lifecycle Source: https://developer.samsung.com/health/blog/en/2022/02/16/tracking-exercises-with-galaxy-watch Provides methods to start an exercise session with a configuration, register an update listener, and terminate the exercise session. ```Java ListenableFuture startExerciseListenableFuture = exerciseClient.startExercise(exerciseConfigBuilder.build()); ListenableFuture updateListenableFuture = exerciseClient.setUpdateListener(exerciseUpdateListener); ListenableFuture endExerciseListenableFuture = exerciseClient.endExercise(); ``` -------------------------------- ### GET /projects/{projectId}/tasks Source: https://developer.samsung.com/health/stack/developer-guide/portal-REST-API-reference/all-endpoints/platform-api-endpoints.html Retrieves a list of tasks for a given project. You can filter the results by specifying start time, end time, last sync time, status, and type. ```APIDOC ## GET /projects/{projectId}/tasks ### Description Retrieves a list of tasks for a given project. You can filter the results by specifying start time, end time, last sync time, status, and type. ### Method GET ### Endpoint `/projects/{projectId}/tasks` ### Parameters #### Path Parameters - **projectId** (string) - Required - Provide the id of the project to retrieve. #### Query Parameters - **start_time** (string(date-time)) - Optional - If not provided, retrieves all tasks created after start_time. - **end_time** (string(date-time)) - Optional - If not provided, retrieves all tasks created before end_time. - **last_sync_time** (string(date-time)) - Optional - (For mobile application) Retrieve tasks that were published after last_sync_time. - **status** (string) - Optional - If not provided, retrieves all tasks regardless of status. Possible values: DRAFT, PUBLISHED. - **type** (string) - Optional - If not provided, retrieves all tasks regardless of type. Possible values: SURVEY, ACTIVITY. ### Request Example ```json { "example": "request body" } ``` ### Response #### Success Response (200) - **revisionId** (integer) - Description - **id** (string) - Description - **title** (string) - Description - **description** (string) - Description - **schedule** (string) - Description - **startTime** (string) - Description - **endTime** (string) - Description - **validTime** (integer) - Description - **status** (string) - Description - **type** (string) - Description - **items** (array) - Description - **name** (string) - Description - **type** (string) - Description - **contents** (object) - Description - **title** (string) - Description - **explanation** (string) - Description - **required** (boolean) - Description - **type** (string) - Description - **properties** (object) - Description - **tag** (string) - Description - **options** (array) - Description - **value** (string) - Description - **label** (string) - Description - **display_logic** (object) - Description - **skip_logic** (array) - Description - **condition** (string) - Description - **goToAction** (null) - Description - **goToItemSequence** (integer) - Description - **sequence** (integer) - Description #### Response Example ```json [ { "revisionId": 0, "id": "string", "title": "string", "description": "string", "schedule": "0 0/1 * 1/1 * ? *", "startTime": "2019-08-24T14:15:22Z", "endTime": "2019-08-24T14:15:22Z", "validTime": 0, "status": "DRAFT", "type": "SURVEY", "items": [ { "name": "string", "type": "QUESTION", "contents": { "title": "string", "explanation": "string", "required": true, "type": "CHOICE", "properties": { "tag": "RADIO", "options": [ { "value": "string", "label": "string" } ], "display_logic": {}, "skip_logic": [ { "condition": "Or contains val4 1 notcontains val4 2", "goToAction": null, "goToItemSequence": 3 } ] } }, "sequence": 0 } ] } ] ``` ``` -------------------------------- ### Configure Backend Environment Variables Source: https://developer.samsung.com/health/research/developer-guide/installation/install-backend.md Configuration template for setting sensitive credentials including PostgreSQL passwords and SMTP relay settings for email services. ```text POSTGRES_PASSWORD= SMTP_HOST= SMTP_PORT= MAIL_USER= MAIL_USER_PASSWORD= ``` -------------------------------- ### Get Current Device Object Source: https://developer.samsung.com/health/android/data/api-reference/com/samsung/android/sdk/healthdata/HealthDeviceManager.html Retrieves the HealthDevice object representing the current device where Samsung Health is installed. This method may throw an IllegalStateException if the data store connection is invalid. ```java public HealthDevice getLocalDevice() throws IllegalStateException { // Method implementation } ``` -------------------------------- ### Reading Latest Blood Pressure (Data SDK) Source: https://developer.samsung.com/health/android/migration-guide/overview.html This section provides code examples for reading the most recent blood pressure data using the Samsung Health Data SDK. ```APIDOC ## Reading the latest blood pressure data with Samsung Health Data SDK ### Description Retrieves the most recent blood pressure reading recorded in Samsung Health using the Samsung Health Data SDK. ### Method N/A (This is a client-side SDK function) ### Endpoint N/A (This is a client-side SDK function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```kotlin suspend fun readLatestBloodPressure( healthDataStore: HealthDataStore ) { val resultCount = 1 val readRequest = DataTypes.BLOOD_PRESSURE.readDataRequestBuilder .setOrdering(Ordering.DESC) .setLimit(resultCount) .build() try { val result = healthDataStore.readData(readRequest) result.dataList.lastOrNull()?.let { dataPoint -> val startTime = dataPoint.startTime val systolicPressure = dataPoint.getValue(DataType.BloodPressureType.SYSTOLIC) val diastolicPressure = dataPoint.getValue(DataType.BloodPressureType.DIASTOLIC) val mean = dataPoint.getValue(DataType.BloodPressureType.MEAN) val pulse = dataPoint.getValue(DataType.BloodPressureType.PULSE_RATE) val sourcePackageName = dataPoint.dataSource?.appId val sourceDeviceId = dataPoint.dataSource?.deviceId } } catch (e: Exception) { e.printStackTrace() } } ``` ### Response #### Success Response (200) N/A (This is a client-side SDK function, results are returned directly) #### Response Example N/A ``` -------------------------------- ### Preview UI Components Source: https://developer.samsung.com/health/research/developer-guide/SDK-Documentation/references/kit/healthstack.kit.task.signup.view/index.html These functions provide previews for the Sign-Up and Registration views within the Android Studio IDE, allowing developers to visualize the UI without deploying to a device. ```kotlin @Preview(showBackground = true) @Composable fun GoogleSignInButtonPreview() { GoogleSignInButton(onClick = {}) } @Preview(showBackground = true) @Composable fun SignUpViewPreview() { // Preview for SignUpView } ``` -------------------------------- ### Reading Latest Blood Pressure (Android SDK) Source: https://developer.samsung.com/health/android/migration-guide/overview.html This section provides code examples for reading the most recent blood pressure data using the Samsung Health SDK for Android. ```APIDOC ## Reading the latest blood pressure data with Samsung Health SDK for Android ### Description Retrieves the most recent blood pressure reading recorded in Samsung Health using the Android SDK. ### Method N/A (This is a client-side SDK function) ### Endpoint N/A (This is a client-side SDK function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```kotlin fun readLatestBloodPressure( healthDataStore: HealthDataStore ) { val resultOffset = 0; val resultCount = 1 val handler = Handler(Looper.getMainLooper()) val healthDataResolver = HealthDataStore(healthDataStore, handler) val request: HealthDataResolver.ReadRequest = HealthDataResolver.ReadRequest.Builder() .setDataType(HealthConstants.BloodPressure.HEALTH_DATA_TYPE) .setSort(HealthConstants.BloodPressure.START_TIME, SortOrder.DESC) .setResultCount(resultOffset, resultCount) .build() try { healthDataResolver.read(request).setResultListener { result -> try { result?.lastOrNull()?.let { healthData -> val startTime = Instant.ofEpochMilli(healthData.getLong(HealthConstants.BloodPressure.START_TIME)) val systolicPressure = healthData.getFloat(HealthConstants.BloodPressure.SYSTOLIC) val diastolicPressure = healthData.getFloat(HealthConstants.BloodPressure.DIASTOLIC) val mean = healthData.getFloat(HealthConstants.BloodPressure.MEAN) val pulse = healthData.getInt(HealthConstants.BloodPressure.PULSE) val sourcePackageName = healthData.getString(HealthConstants.Common.PACKAGE_NAME) val sourceDeviceID = healthData.getString(HealthConstants.Common.DEVICE_UUID) } } finally { result.close() } } } catch (e: Exception) { e.printStackTrace() } } ``` ### Response #### Success Response (200) N/A (This is a client-side SDK function, results are returned via callback) #### Response Example N/A ``` -------------------------------- ### Initialize and Retrieve HealthStackBackendAdapter Source: https://developer.samsung.com/health/research/developer-guide/SDK-Documentation/references/backend-integration/healthstack-adapter/healthstack.backend.integration.adapter/-health-stack-backend-adapter/-companion/index.html Demonstrates how to initialize the HealthStackBackendAdapter with a platform endpoint and project ID, and how to retrieve the singleton instance of the adapter. ```kotlin import healthstack.backend.integration.adapter.HealthStackBackendAdapter // Initialize the adapter HealthStackBackendAdapter.initialize("https://api.example.com", "project_id_123") // Get the singleton instance val adapter = HealthStackBackendAdapter.getInstance() ``` -------------------------------- ### Create HealthDataPoint for Exercise Sessions Source: https://developer.samsung.com/health/android/migration-guide/exercise-app-example.html Shows how to build an ExerciseSession and encapsulate it within a HealthDataPoint. This requires defining exercise metadata, duration, and the associated list of logs. ```kotlin val calories = 73f val distance = 1000f val startTime = Instant.ofEpochSecond(1766394000) val endTime = Instant.ofEpochSecond(1766394300) val duration = Duration.between(startTime, endTime) var healthDataPoint: HealthDataPoint? try { val session = ExerciseSession.builder() .setStartTime(startTime) .setEndTime(endTime) .setExerciseType(DataType.ExerciseType.PredefinedExerciseType.RUNNING) .setDuration(duration) .setCalories(calories) .setDistance(distance) .setComment("Routine running") .setLog(exerciseLog) .build() healthDataPoint = HealthDataPoint.builder() .setStartTime(startTime) .setEndTime(endTime) .addFieldData( DataType.ExerciseType.EXERCISE_TYPE, DataType.ExerciseType.PredefinedExerciseType.RUNNING ) .addFieldData(DataType.ExerciseType.SESSIONS, listOf(session)) .build() } catch (e: Exception) { throw e } ``` -------------------------------- ### Configure Firebase Application ID Source: https://developer.samsung.com/health/research/developer-guide/installation/install-sdk.md Sets the application ID required for Firebase integration within the Android project structure. This identifier must match the configuration in the google-services.json file. ```gradle applicationId = "healthstack.sample" ``` -------------------------------- ### Read daily total water intake Source: https://developer.samsung.com/health/android/migration-guide/overview.html Retrieves the sum of water intake for the current day. It utilizes time-range filtering to aggregate data points between the start of the day and the current time. ```Kotlin (Samsung Health SDK) fun readTodayTotalWaterIntake (healthDataStore: HealthDataStore) { val startTime = LocalDate.now().atStartOfDay().toInstant(ZoneOffset.UTC).toEpochMilli() val endTime = LocalDateTime.now().toInstant(ZoneOffset.UTC).toEpochMilli() val handler = Handler(Looper.getMainLooper()) val healthDataResolver = HealthDataResolver(healthDataStore, handler) val waterIntakeId = "water_intake_sum" val aggregateRequest = HealthDataResolver.AggregateRequest.Builder() .addFunction(HealthDataResolver.AggregateRequest.AggregateFunction.SUM, HealthConstants.WaterIntake.AMOUNT, waterIntakeId) .setLocalTimeRange(HealthConstants.WaterIntake.START_TIME, HealthConstants.WaterIntake.TIME_OFFSET, startTime, endTime) .setDataType(HealthConstants.WaterIntake.HEALTH_DATA_TYPE).build() try { healthDataResolver.aggregate(aggregateRequest).setResultListener { result -> try { result?.forEach { healthData -> val waterIntakeSum = healthData.getFloat(waterIntakeId) } } finally { result.close() } } } catch (e: Exception) { e.printStackTrace() } } ``` ```Kotlin (Samsung Health Data SDK) suspend fun readTodayTotalWaterIntake(healthDataStore: com.samsung.android.sdk.health.data.HealthDataStore) { val startTime = LocalDate.now().atStartOfDay() val endTime = LocalDateTime.now() val localTimeFilter = LocalTimeFilter.of(startTime, endTime) val readRequest = DataType.WaterIntakeType.TOTAL.requestBuilder .setLocalTimeFilter(localTimeFilter) .build() try { val result = healthDataStore.aggregateData(readRequest) result.dataList.lastOrNull()?.let { dataPoint -> val waterIntake = dataPoint.value } } catch (e: Exception) { e.printStackTrace() } } ``` -------------------------------- ### Implement Jetpack Compose Previews for Onboarding Views Source: https://developer.samsung.com/health/research/developer-guide/SDK-Documentation/references/kit/healthstack.kit.task.onboarding.view/index.html Provides Composable functions annotated with @Preview to visualize onboarding UI components during development. These functions allow developers to verify layout states like success or failure results in the Android Studio preview pane. ```kotlin @Preview(showBackground = true) @Composable fun EligibilityResultViewSuccessPreview() { // Implementation for success state preview } @Composable fun IntroSections(sections: List) { // Implementation for rendering intro sections } ``` -------------------------------- ### Write Body Temperature Data Source: https://developer.samsung.com/health/android/migration-guide/overview.html Provides implementations for inserting body temperature records. Includes examples for both the legacy Samsung Health SDK for Android and the current Samsung Health Data SDK. ```kotlin fun insertBodyTemperatureData( healthDataStore: HealthDataStore ) { val bodyTemperature = 37F val tenMinutesAsSeconds = 10L * 60L val zoneId = ZoneOffset.systemDefault() val startTime = LocalDateTime.now().minusSeconds(tenMinutesAsSeconds).atZone(zoneId) .toInstant().toEpochMilli() val timeOffset = TimeZone.getDefault().getOffset(startTime).toLong() val mHealthDataResolver = HealthDataResolver(healthDataStore, Handler(Looper.getMainLooper())) val healthDeviceManager = HealthDeviceManager(healthDataStore) val data = HealthData().apply { putLong(HealthConstants.BodyTemperature.START_TIME, startTime) putLong(HealthConstants.BodyTemperature.TIME_OFFSET, timeOffset) putFloat(HealthConstants.BodyTemperature.TEMPERATURE, bodyTemperature) sourceDevice = healthDeviceManager.localDevice.uuid } try { val insertRequest = InsertRequest.Builder() .setDataType(HealthConstants.BodyTemperature.HEALTH_DATA_TYPE) .build() insertRequest.addHealthData(data) val result = mHealthDataResolver.insert(insertRequest).await() Log.i(MainActivity.APP_TAG, "insert result status: ${result.status}") } catch (e: Exception) { e.printStackTrace() } } ``` ```kotlin suspend fun insertBodyTemperatureData( healthDataStore: HealthDataStore ) { val bodyTemperature = 37F val tenMinutesAsSeconds = 10L * 60L val time = LocalDateTime.now().minusSeconds(tenMinutesAsSeconds) val zoneId = ZoneOffset.systemDefault() val zoneOffset = zoneId.rules.getOffset(time) try { val healthDataPoint = HealthDataPoint.builder() .addFieldData(DataType.BodyTemperatureType.BODY_TEMPERATURE, bodyTemperature) .setLocalStartTime(time, zoneOffset) .setLocalEndTime(time, zoneOffset) .build() val insertRequest = DataTypes.BODY_TEMPERATURE.insertDataRequestBuilder .addData(healthDataPoint) .build() healthDataStore.insertData(insertRequest) } catch (e: Exception) { e.printStackTrace() } } ``` -------------------------------- ### POST /auth/signup Source: https://developer.samsung.com/health/stack/developer-guide/portal-REST-API-reference/all-endpoints/account-service-api-endpoints.html Registers a new user account with email, password, and profile information. ```APIDOC ## POST /auth/signup ### Description Creates a new user account in the system. ### Method POST ### Endpoint /auth/signup ### Request Body - **email** (string) - Required - User email address - **password** (string) - Required - User password - **profile** (object) - Required - User account details ### Request Example { "email": "cubist@samsung.com", "password": "string", "profile": { "name": "david.lee", "status": "active" } } ``` -------------------------------- ### Read Today's Heart Rate Data (Method 1) Source: https://developer.samsung.com/health/android/migration-guide/overview.html This section provides an example of how to read today's heart rate data using the Samsung Health SDK for Android with `HealthDataResolver`. ```APIDOC ## Read Today's Heart Rate Data (Method 1) ### Description This endpoint demonstrates reading today's heart rate data using the `HealthDataResolver` class from the Samsung Health SDK. ### Method N/A (This is a code example for an Android SDK function) ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example ```kotlin class ReadHeartRate { fun readTodayHeartRate( healthDataStore: HealthDataStore ) { val startTime = LocalDate.now().atStartOfDay().toInstant(ZoneOffset.UTC).toEpochMilli() val endTime = LocalDateTime.now().toInstant(ZoneOffset.UTC).toEpochMilli() val handler = Handler(Looper.getMainLooper()) val healthDataResolver = HealthDataStore(healthDataStore, handler) val request: HealthDataResolver.ReadRequest = HealthDataResolver.ReadRequest.Builder() .setDataType(HealthConstants.HeartRate.HEALTH_DATA_TYPE) .setLocalTimeRange( HealthConstants.HeartRate.START_TIME, HealthConstants.HeartRate.TIME_OFFSET, startTime, endTime ).build() try { healthDataResolver.read(request).setResultListener { result -> try { result?.forEach { healthData -> val heartRate = healthData.getFloat(HealthConstants.HeartRate.HEART_RATE) val measurementStartTime = Instant.ofEpochMilli(healthData.getLong(HealthConstants.HeartRate.START_TIME)) val measurementEndTime = Instant.ofEpochMilli(healthData.getLong(HealthConstants.HeartRate.END_TIME)) val binningData = healthData.getBlob(HealthConstants.HeartRate.BINNING_DATA) val liveDataList = HealthDataUtil.getStructuredDataList( binningData, HeartRateLiveData::class.java ) liveDataList.forEach { liveDataPoint -> val heartRate = liveDataPoint.heart_rate val startTime = Instant.ofEpochMilli(liveDataPoint.start_time) } } } finally { result.close() } } } catch (e: Exception) { e.printStackTrace() } } } data class HeartRateLiveData( val heart_rate: Float, val heart_rate_min: Float, val heart_rate_max: Float, val start_time: Long, val end_time: Long ) ``` ### Response #### Success Response (200) N/A (This is a code example for an Android SDK function) #### Response Example N/A ``` -------------------------------- ### Read latest blood pressure data Source: https://developer.samsung.com/health/android/migration-guide/overview.html Retrieves the most recent blood pressure record from the health data store. This implementation handles sorting by start time in descending order to ensure the latest entry is fetched. ```Kotlin (Samsung Health SDK for Android) fun readLatestBloodPressure( healthDataStore: HealthDataStore ) { val resultOffset = 0; val resultCount = 1 val handler = Handler(Looper.getMainLooper()) val healthDataResolver = HealthDataResolver(healthDataStore, handler) val request: HealthDataResolver.ReadRequest = HealthDataResolver.ReadRequest.Builder() .setDataType(HealthConstants.BloodPressure.HEALTH_DATA_TYPE) .setSort(HealthConstants.BloodPressure.START_TIME, SortOrder.DESC) .setResultCount(resultOffset, resultCount) .build() try { healthDataResolver.read(request).setResultListener { result -> try { result?.lastOrNull()?.let { healthData -> val startTime = Instant.ofEpochMilli(healthData.getLong(HealthConstants.BloodPressure.START_TIME)) val systolicPressure = healthData.getFloat(HealthConstants.BloodPressure.SYSTOLIC) val diastolicPressure = healthData.getFloat(HealthConstants.BloodPressure.DIASTOLIC) val mean = healthData.getFloat(HealthConstants.BloodPressure.MEAN) val pulse = healthData.getInt(HealthConstants.BloodPressure.PULSE) val sourcePackageName = healthData.getString(HealthConstants.Common.PACKAGE_NAME) val sourceDeviceID = healthData.getString(HealthConstants.Common.DEVICE_UUID) } } finally { result.close() } } } catch (e: Exception) { e.printStackTrace() } } ``` ```Kotlin (Samsung Health Data SDK) suspend fun readLatestBloodPressure( healthDataStore: HealthDataStore ) { val resultCount = 1 val readRequest = DataTypes.BLOOD_PRESSURE.readDataRequestBuilder .setOrdering(Ordering.DESC) .setLimit(resultCount) .build() try { val result = healthDataStore.readData(readRequest) result.dataList.lastOrNull()?.let { dataPoint -> val startTime = dataPoint.startTime val systolicPressure = dataPoint.getValue(DataType.BloodPressureType.SYSTOLIC) val diastolicPressure = dataPoint.getValue(DataType.BloodPressureType.DIASTOLIC) val mean = dataPoint.getValue(DataType.BloodPressureType.MEAN) val pulse = dataPoint.getValue(DataType.BloodPressureType.PULSE_RATE) val sourcePackageName = dataPoint.dataSource?.appId val sourceDeviceId = dataPoint.dataSource?.deviceId } } catch (e: Exception) { e.printStackTrace() } } ``` -------------------------------- ### Token String Example Source: https://developer.samsung.com/health/stack/developer-guide/portal-REST-API-reference/all-endpoints/account-service-api-endpoints.html A placeholder string representing a generic token. ```text "aadfad...badfdfad" ```