### Hello Health Data Quick Start Source: https://developer.samsung.com/health/android/data/guide/process A quick start guide for integrating Samsung Health data into your Android application. It demonstrates how to read and write health data. ```java /* * This is a sample code snippet for the Hello Health Data example. * It demonstrates basic interaction with the Samsung Health API. * Please refer to the official documentation for complete implementation details. */ // Import necessary Samsung Health SDK classes import com.samsung.android.sdk.healthdata.HealthConnectionError; import com.samsung.android.sdk.healthdata.HealthConstants; import com.samsung.android.sdk.healthdata.HealthData; import com.samsung.android.sdk.healthdata.HealthDataService; import com.samsung.android.sdk.healthdata.HealthDataStore; import com.samsung.android.sdk.healthdata.HealthDataObserver; import com.samsung.android.sdk.healthdata.HealthDevice; import com.samsung.android.sdk.healthdata.HealthDeviceManager; import com.samsung.android.sdk.healthdata.HealthResultReceiver; import com.samsung.android.sdk.healthdata.HealthService; import android.content.Context; import android.os.Bundle; import android.os.Handler; import android.util.Log; public class HelloHealthData { private HealthDataStore mStore; private HealthConnectionError mConnError; private static final String TAG = "HelloHealthData"; // Initialize the HealthDataStore public void initializeHealthData(Context context) { mStore = new HealthDataStore(); mStore.initialize(context, new HealthDataService.ServiceListener() { @Override public void onInitialized() { Log.i(TAG, "HealthDataService is initialized."); // You can now start accessing Samsung Health data // Example: Requesting a specific data type (e.g., step count) // readStepCount(); } @Override public void onConnectionFailed(HealthConnectionError error) { Log.e(TAG, "HealthDataService connection failed: " + error.getErrorCode()); mConnError = error; // Handle connection error appropriately } @Override public void onDisconnected() { Log.i(TAG, "HealthDataService disconnected."); // Handle disconnection } }); } // Example method to read step count public void readStepCount(HealthResultReceiver receiver) { if (mStore == null) { Log.e(TAG, "HealthDataStore is not initialized."); return; } // Create a HealthData object for step count HealthData data = new HealthData(); data.put(HealthConstants.StepCount.COUNT, "*"); // '*' means all available data // Specify the data type and time range (optional) // For step count, the data type is HealthConstants.StepCount.HEALTH_DATA_TYPE String dataType = HealthConstants.StepCount.HEALTH_DATA_TYPE; // Execute the read request mStore.readData(receiver, dataType, data, null); } // Example method to write custom data (e.g., calories) public void writeCalories(HealthData data, HealthResultReceiver receiver) { if (mStore == null) { Log.e(TAG, "HealthDataStore is not initialized."); return; } // Specify the data type for calories String dataType = HealthConstants.Nutrition.HEALTH_DATA_TYPE; // Execute the write request mStore.insertData(receiver, dataType, data); } // Remember to close the connection when done public void closeHealthData() { if (mStore != null) { mStore.close(); mStore = null; Log.i(TAG, "HealthDataStore closed."); } } } ``` -------------------------------- ### Read Today's Body Temperature Data with Samsung Health SDK for Android Source: https://developer.samsung.com/health/android/migration-guide/overview This example demonstrates reading today's body temperature data using Samsung Health SDK for Android. It configures a read request with a data type and time range, then uses a result listener to process the retrieved data, extracting measurement start time and temperature. ```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() } } ``` -------------------------------- ### Asynchronous Read Request for Steps with Samsung Health SDK for Android Source: https://developer.samsung.com/health/android/migration-guide/overview Provides an example of making an asynchronous read request for daily step trends using the Samsung Health SDK. It demonstrates filtering data by date and source type, then processing the results. ```kotlin fun readStepsAsync(healthDataStore: HealthDataStore) { val healthDataResolver = HealthDataResolver(healthDataStore, null) val date = LocalDate .now() .atStartOfDay() .toInstant(ZoneOffset.UTC) .toEpochMilli() val filter = Filter.and( Filter.eq(StepDailyTrend.DAY_TIME, date), Filter.eq(StepDailyTrend.SOURCE_TYPE, StepDailyTrend.SOURCE_TYPE_ALL) ) val stepsRequest = HealthDataResolver.ReadRequest.Builder() .setDataType(StepDailyTrend.HEALTH_DATA_TYPE) .setFilter(filter) .build() try { healthDataResolver.read(stepsRequest).setResultListener { result -> try { val iterator = result.iterator() if (iterator.hasNext()) { val healthData = iterator.next() val stepCount = healthData.getInt(StepDailyTrend.COUNT) Log.i(MainActivity.APP_TAG, "Step count: $stepCount") } } finally { result.close() } } } catch (exception: Exception) { exception.message?.let { Log.i(MainActivity.APP_TAG, it) } } } ``` -------------------------------- ### Reading Today's Body Temperature Data (Samsung Health SDK for Android) Source: https://developer.samsung.com/health/android/migration-guide/overview This example shows how to read the current day's body temperature data using the Samsung Health SDK for Android. ```APIDOC ## GET /readTodayBodyTemperature ### Description Reads today's body temperature data from Samsung Health using the Samsung Health SDK for Android. ### Method GET ### Endpoint /readTodayBodyTemperature ### Parameters #### 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) Returns a list of body temperature data points for the current day. #### Response Example ```json [ { "startTime": "2023-10-27T08:00:00Z", "temperature": 36.5 } ] ``` ``` -------------------------------- ### Reading Today's Body Temperature Data (Samsung Health Data SDK) Source: https://developer.samsung.com/health/android/migration-guide/overview This snippet provides an example of reading today's body temperature data using the Samsung Health Data SDK. ```APIDOC ## GET /readTodayBodyTemperature ### Description Reads today's body temperature data from Samsung Health using the Samsung Health Data SDK. ### Method GET ### Endpoint /readTodayBodyTemperature ### Parameters #### Request Body - **healthDataStore** (HealthDataStore) - Required - The HealthDataStore instance. ### Request Example ```kotlin // Example not provided in the source text, but would follow a similar pattern to the SDK example above. // To implement this, you would use DataTypes.BODY_TEMPERATURE.readDataRequestBuilder and healthDataStore.readData() ``` ### Response #### Success Response (200) Returns a list of body temperature data points for the current day. #### Response Example ```json [ { "startTime": "2023-10-27T08:00:00Z", "temperature": 36.5 } ] ``` ``` -------------------------------- ### Reading Blood Glucose Data - Samsung Health SDK for Android Source: https://developer.samsung.com/health/android/migration-guide/overview This section provides an example of reading today's blood glucose data using the Samsung Health SDK for Android. It shows how to configure a read request and process the returned HealthData. ```APIDOC ## GET /healthdata/bloodglucose ### Description Reads today's blood glucose data from the Samsung Health store using the Android SDK. ### Method GET ### Endpoint `/healthdata/bloodglucose` ### Parameters #### Request Body - **healthDataStore** (HealthDataStore) - Required - The HealthDataStore instance to use for data operations. ### Request Example ```kotlin fun readTodayBloodGlucose ( 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 request: HealthDataResolver.ReadRequest = HealthDataResolver.ReadRequest.Builder() .setDataType(HealthConstants.BloodGlucose.HEALTH_DATA_TYPE) .setLocalTimeRange( HealthConstants.OxygenSaturation.START_TIME, HealthConstants.OxygenSaturation.TIME_OFFSET, startTime, endTime ).build() try { healthDataResolver.read(request).setResultListener { result -> try { result.forEach { healthData -> val measurementStartTime = Instant.ofEpochMilli(healthData.getLong(HealthConstants.BloodGlucose.START_TIME)) val bloodGlucose = healthData.getFloat(HealthConstants.BloodGlucose.GLUCOSE) //Refer to the documentation for MEAL_TYPE, MEASUREMENT_TYPE, SAMPLE_SOURCE_TYPE mapping val mealType = healthData.getInt(HealthConstants.BloodGlucose.MEAL_TYPE) val measurementType = healthData.getInt(HealthConstants.BloodGlucose.MEASUREMENT_TYPE) val sampleSourceType = healthData.getInt(HealthConstants.BloodGlucose.SAMPLE_SOURCE_TYPE) } } finally { result.close() } } } catch (e: Exception) { e.printStackTrace() } } ``` ### Response #### Success Response (200) - **measurementStartTime** (Instant) - The start time of the blood glucose measurement. - **bloodGlucose** (Float) - The measured blood glucose value. - **mealType** (Int) - The type of meal associated with the measurement (refer to documentation for mapping). - **measurementType** (Int) - The type of measurement (refer to documentation for mapping). - **sampleSourceType** (Int) - The source of the sample data (refer to documentation for mapping). #### Response Example ```json { "measurementStartTime": "2023-10-27T10:00:00Z", "bloodGlucose": 120.5, "mealType": 1, "measurementType": 2, "sampleSourceType": 3 } ``` ``` -------------------------------- ### Requesting Step Data with Samsung Health Data SDK (Kotlin) Source: https://developer.samsung.com/health/android/migration-guide/overview This code snippet demonstrates how to request total step data within a specified time range using the Samsung Health Data SDK in Kotlin. It defines start and end times, creates a time filter, and builds a request for step data. ```kotlin val startTime = LocalDate.now().atStartOfDay() val endTime = LocalDateTime.now() val localTimeFilter = LocalTimeFilter.of(startTime, endTime) val stepsRequest = DataType.StepsType.TOTAL.requestBuilder .setLocalTimeFilter(localTimeFilter) .build() ``` -------------------------------- ### Writing Floors Climbed Data (SDK) Source: https://developer.samsung.com/health/android/migration-guide/overview Demonstrates how to write floors climbed data using the Samsung Health SDK for Android. ```APIDOC ## Writing Floors Climbed Data with Samsung Health SDK for Android ### Description This function inserts a record of floors climbed for the current time using the HealthDataResolver. ### Method `fun insertTodayFloorsClimbed(healthDataStore: HealthDataStore)` ### Endpoint N/A (SDK function) ### Parameters - **healthDataStore** (HealthDataStore) - Required - An instance of HealthDataStore to access Samsung Health data. ### Request Body N/A (Data is constructed within the function) ### Request Example (Data is constructed internally. The function takes `healthDataStore` as input.) ### Response #### Success Response Logs the success of the insertion and the count of data inserted, or logs that the insertion failed. #### Response Example ``` Log.i(MainActivity.APP_TAG, "Inserted floor climbed. Count of data: 1") ``` ### Error Handling Prints the stack trace of any exceptions encountered during the insert operation. ``` -------------------------------- ### Writing Floors Climbed Data (Data SDK) Source: https://developer.samsung.com/health/android/migration-guide/overview Demonstrates how to write floors climbed data using the Samsung Health Data SDK. ```APIDOC ## Writing Floors Climbed Data with Samsung Health Data SDK ### Description This suspend function inserts a record of floors climbed for the current time using the HealthDataStore's insertData method. ### Method `suspend fun insertTodayFloorClimbed(healthDataStore: HealthDataStore)` ### Endpoint N/A (SDK function) ### Parameters - **healthDataStore** (HealthDataStore) - Required - An instance of HealthDataStore to access Samsung Health data. ### Request Body N/A (Data is constructed within the function) ### Request Example (Data is constructed internally. The function takes `healthDataStore` as input.) ### Response #### Success Response Logs a success message indicating that the floor climbed data was inserted. #### Response Example ``` Log.i(MainActivity.APP_TAG, "Inserted floor climbed") ``` ### Error Handling Prints the stack trace of any exceptions encountered during the insert operation. ``` -------------------------------- ### Write Body Temperature Data with Samsung Health SDK for Android Source: https://developer.samsung.com/health/android/migration-guide/overview Writes body temperature data using the Samsung Health SDK for Android. It creates a HealthData object with temperature, start time, and time offset, then inserts it into the HealthDataStore. ```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) // Register local device as the source of data 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() } } ``` -------------------------------- ### Write Blood Pressure Data with Samsung Health SDK for Android Source: https://developer.samsung.com/health/android/migration-guide/overview This snippet demonstrates how to write blood pressure data (systolic, diastolic, mean) to Samsung Health using the HealthDataStore and HealthDataResolver. It requires the HealthDataStore and sets a start time, time offset, and blood pressure values. ```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() } } ``` -------------------------------- ### Read Latest Weight Data with Samsung Health SDK for Android (Kotlin) Source: https://developer.samsung.com/health/android/migration-guide/overview This function demonstrates how to read the latest weight data using the Samsung Health SDK for Android. It utilizes HealthDataResolver to query for weight, body fat, and start time, requesting the most recent entry. ```kotlin fun readLatestWeight( healthDataStore: HealthDataStore ) { val resultCount = 1 val resultOffset = 0 val handler = Handler(Looper.getMainLooper()) val healthDataResolver = HealthDataResolver(healthDataStore, handler) val request: HealthDataResolver.ReadRequest = HealthDataResolver.ReadRequest.Builder() .setDataType(HealthConstants.Weight.HEALTH_DATA_TYPE) .setSort(HealthConstants.OxygenSaturation.START_TIME, SortOrder.DESC) .setResultCount(resultOffset, resultCount) .build() try { healthDataResolver.read(request).setResultListener { result -> try { result.lastOrNull()?.let { healthData -> val measurementStartTime = Instant.ofEpochMilli(healthData.getLong(HealthConstants.Weight.START_TIME)) val weight = healthData.getFloat(HealthConstants.Weight.WEIGHT) val bodyFat = healthData.getFloat(HealthConstants.Weight.BODY_FAT) } } finally { result.close() } } } catch (e: Exception) { e.printStackTrace() } } ``` -------------------------------- ### Write Weight Data with Samsung Health Data SDK Source: https://developer.samsung.com/health/android/migration-guide/overview Writes weight data to Samsung Health using the newer Samsung Health Data SDK. It creates a HealthDataPoint with the weight value and sets the local start time. This data point is then added to an InsertRequest for the BODY_COMPOSITION data type, which is subsequently inserted into the health data store. Exceptions during insertion are caught and printed. ```kotlin suspend fun insertWeightData( healthDataStore: HealthDataStore ) { val weight = 75F val localDateTime = LocalDate.now().atTime(9, 0) val zoneId = ZoneOffset.systemDefault() val zoneOffset = zoneId.rules.getOffset(localDateTime) try { val healthDataPoint = HealthDataPoint.builder() .addFieldData(DataType.BodyCompositionType.WEIGHT, weight) .setLocalStartTime(localDateTime, zoneOffset) .build() val insertRequest = DataTypes.BODY_COMPOSITION.insertDataRequestBuilder .addData(healthDataPoint) .build() healthDataStore.insertData(insertRequest) } catch (e: Exception) { e.printStackTrace() } } ``` -------------------------------- ### Write Weight Data with Samsung Health SDK for Android Source: https://developer.samsung.com/health/android/migration-guide/overview Writes weight data to Samsung Health using the older Samsung Health SDK for Android. It constructs a HealthData object containing weight, start time, and time offset, then uses an InsertRequest to add this data via the HealthDataResolver. The function logs the insertion result status and catches any exceptions. ```kotlin fun insertWeightData( healthDataStore: HealthDataStore ) { val weight = 75F val zoneId = ZoneOffset.systemDefault() val startTime = LocalDate.now().atTime(9, 0).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.Weight.START_TIME, startTime) putLong(HealthConstants.Weight.TIME_OFFSET, timeOffset) putFloat(HealthConstants.Weight.WEIGHT, weight) // Register local device as the source of data sourceDevice = healthDeviceManager.localDevice.uuid } try { val insertRequest = InsertRequest.Builder() .setDataType(HealthConstants.Weight.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() } } ``` -------------------------------- ### Reading Floors Climbed Data (SDK) Source: https://developer.samsung.com/health/android/migration-guide/overview Demonstrates how to read today's floors climbed data using the Samsung Health SDK for Android. ```APIDOC ## Reading Floors Climbed Data with Samsung Health SDK for Android ### Description This function reads the total floors climbed for the current day using the HealthDataResolver. ### Method `fun readTodayFloorsClimbed(healthDataStore: HealthDataStore)` ### Endpoint N/A (SDK function) ### Parameters - **healthDataStore** (HealthDataStore) - Required - An instance of HealthDataStore to access Samsung Health data. ### Request Body N/A ### Response #### Success Response Logs the total floors climbed for the day or '0' if no data is found. #### Response Example ``` Log.i(MainActivity.APP_TAG, "Today floors climbed: 10") ``` ### Error Handling Logs any exceptions encountered during the read operation. ``` -------------------------------- ### Reading Floors Climbed Data (Data SDK) Source: https://developer.samsung.com/health/android/migration-guide/overview Demonstrates how to read today's floors climbed data using the Samsung Health Data SDK. ```APIDOC ## Reading Floors Climbed Data with Samsung Health Data SDK ### Description This suspend function reads the total floors climbed for the current day using the HealthDataStore's aggregateData method. ### Method `suspend fun readTodayFloorsClimbed(healthDataStore: HealthDataStore)` ### Endpoint N/A (SDK function) ### Parameters - **healthDataStore** (HealthDataStore) - Required - An instance of HealthDataStore to access Samsung Health data. ### Request Body N/A ### Response #### Success Response Logs the total floors climbed for the day (defaults to 0 if no data is found). #### Response Example ``` Log.i(MainActivity.APP_TAG, "Today floors climbed: 15") ``` ### Error Handling Prints the stack trace of any exceptions encountered during the read operation. ``` -------------------------------- ### Get User Profile Data with Samsung Health SDK for Android Source: https://developer.samsung.com/health/android/migration-guide/overview Retrieves user profile data, including gender, height, and weight, using the Samsung Health SDK for Android. It provides a helper function to map gender ID to a string. ```kotlin fun readUserProfile( healthDataStore: HealthDataStore ) { val userProfile = HealthUserProfile.getProfile(healthDataStore) val gender = genderNameById(userProfile.gender) val height = userProfile.height val weight = userProfile.weight } fun genderNameById(id: Int): String { return when (id) { HealthUserProfile.GENDER_MALE -> "MALE" HealthUserProfile.GENDER_FEMALE -> "FEMALE" else -> "UNKNOWN" } } ``` -------------------------------- ### Write Blood Pressure Data with Samsung Health Data SDK Source: https://developer.samsung.com/health/android/migration-guide/overview This snippet shows how to write blood pressure data using the newer Samsung Health Data SDK. It utilizes HealthDataPoint.builder to create a data point with start time and blood pressure values, then inserts it via the HealthDataStore. ```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() } } ``` -------------------------------- ### Writing Blood Pressure Data (Samsung Health SDK for Android) Source: https://developer.samsung.com/health/android/migration-guide/overview This snippet demonstrates how to insert blood pressure data using the Samsung Health SDK for Android. ```APIDOC ## POST /insertBloodPressureData ### Description Inserts blood pressure data into Samsung Health using the Samsung Health SDK for Android. ### Method POST ### Endpoint /insertBloodPressureData ### Parameters #### Request Body - **healthDataStore** (HealthDataStore) - Required - The HealthDataStore instance. ### 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 Status code 200 OK ``` -------------------------------- ### Insert Today Floors Climbed Data with Samsung Health SDK Source: https://developer.samsung.com/health/android/migration-guide/overview Writes floors climbed data to Samsung Health using the Samsung Health SDK. It creates a HealthData object containing the floor count, start time, and end time, then uses HealthDataResolver to insert this data. The function logs the success or failure of the insertion. ```kotlin fun insertTodayFloorsClimbed(healthDataStore: HealthDataStore) { val oneMinuteAsSeconds = 60L val floor = 2f val deviceId = HealthDeviceManager(healthDataStore).localDevice.uuid val startTime = Instant.now().minusSeconds(oneMinuteAsSeconds).toEpochMilli() val endTime = Instant.now().toEpochMilli() val timeOffset = TimeZone.getDefault().getOffset(endTime).toLong() val healthDataResolver = HealthDataResolver(healthDataStore, null) val healthData = HealthData().apply { sourceDevice = deviceId putLong(FloorsClimbed.START_TIME, startTime) putLong(FloorsClimbed.END_TIME, endTime) putLong(FloorsClimbed.TIME_OFFSET, timeOffset) putFloat(FloorsClimbed.FLOOR, floor) } val insertRequest = HealthDataResolver.InsertRequest.Builder() .setDataType(FloorsClimbed.HEALTH_DATA_TYPE) .build() insertRequest.addHealthData(healthData) try { val result = healthDataResolver.insert(insertRequest).await() if (result.status == STATUS_SUCCESSFUL) { Log.i( MainActivity.APP_TAG, "Inserted floor climbed. Count of data: ${result.count}" ) } else { Log.i(MainActivity.APP_TAG, "Inserting failed") } } catch (e: Exception) { e.printStackTrace() } } ``` -------------------------------- ### Insert Nutrition Data with Samsung Health SDK (Kotlin) Source: https://developer.samsung.com/health/android/migration-guide/overview This Kotlin function demonstrates how to insert nutrition data into Samsung Health using the HealthDataStore. It includes details such as meal title, calories, fats, protein, carbohydrates, sugars, fiber, sodium, calcium, iron, and potassium, along with start time and time offset. ```kotlin fun insertNutrition(healthDataStore: HealthDataStore) { val myDevice = HealthDeviceManager(healthDataStore) val mealTitle = "Toast and coffee" val calories = 66f val totalFat = 0.8f val saturatedFat = 0.1f val protein = 2.1f val carbohydrate = 11.9f val totalSugars = 1f val dietaryFiber = 0.6f val sodium = 135f val calcium = 40.3f val iron = 0.78f val potassium = 140f //for females, age 19 - 50, according to https://nap.nationalacademies.org/catalog/11537/dietary-reference-intakes-the-essential-guide-to-nutrient-requirements val referenceIndexForIronInMilligrams = 8.1f // for age 19-50, refer to the link above. val referenceIndexForCalciumInMilligrams = 1000f val startTime = Instant.now().toEpochMilli() val timeOffset = TimeZone.getDefault().getOffset(startTime).toLong() val data = HealthData().apply { sourceDevice = myDevice.localDevice.uuid putLong(HealthConstants.Nutrition.START_TIME, startTime) putLong(HealthConstants.Nutrition.TIME_OFFSET, timeOffset) putInt(HealthConstants.Nutrition.MEAL_TYPE, MEAL_TYPE_BREAKFAST) putString(HealthConstants.Nutrition.TITLE, mealTitle) putFloat(HealthConstants.Nutrition.CALORIE, calories) putFloat(HealthConstants.Nutrition.TOTAL_FAT, totalFat) putFloat(HealthConstants.Nutrition.SATURATED_FAT, saturatedFat) putFloat(HealthConstants.Nutrition.PROTEIN, protein) putFloat(HealthConstants.Nutrition.CARBOHYDRATE, carbohydrate) putFloat(HealthConstants.Nutrition.SUGAR, totalSugars) putFloat(HealthConstants.Nutrition.DIETARY_FIBER, dietaryFiber) putFloat(HealthConstants.Nutrition.SODIUM, sodium) putFloat(HealthConstants.Nutrition.POTASSIUM, potassium) val calciumAsPercentOfReferenceIntake = calcium / referenceIndexForCalciumInMilligrams * 100 val ironInPercentOfReferenceIntake= iron / referenceIndexForIronInMilligrams * 100 putFloat(HealthConstants.Nutrition.CALCIUM, calciumAsPercentOfReferenceIntake) putFloat(HealthConstants.Nutrition.IRON, ironInPercentOfReferenceIntake) } val insertRequest = HealthDataResolver.InsertRequest.Builder() .setDataType(HealthConstants.Nutrition.HEALTH_DATA_TYPE) .build() val handler = Handler(Looper.getMainLooper()) val healthDataResolver = HealthDataResolver(healthDataStore, handler) try { insertRequest.addHealthData(data) val insertResult = healthDataResolver.insert(insertRequest).await() Log.i(TAG, "insertNutrition status: ${insertResult.status}") } catch (e: Exception) { e.printStackTrace() } } ``` -------------------------------- ### Example: Retrieving Permission State Source: https://developer.samsung.com/health/android/data/api-reference/com/samsung/android/sdk/healthdata/HealthPermissionManager An example demonstrating how to retrieve the permission state for a specific permission key from the result map returned by `isPermissionAcquired`. ```java public class HealthPermissionManagerExample { // Example usage of Map.get(Object) } ``` -------------------------------- ### Writing Blood Pressure Data (Samsung Health Data SDK) Source: https://developer.samsung.com/health/android/migration-guide/overview This snippet shows how to insert blood pressure data using the Samsung Health Data SDK. ```APIDOC ## POST /insertBloodPressureData ### Description Inserts blood pressure data into Samsung Health using the Samsung Health Data SDK. ### Method POST ### Endpoint /insertBloodPressureData ### Parameters #### Request Body - **healthDataStore** (HealthDataStore) - Required - The HealthDataStore instance. ### 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 Status code 200 OK ``` -------------------------------- ### Gradle: Apply Kotlin Parcelize Plugin Source: https://developer.samsung.com/health/android/migration-guide/overview This Gradle configuration applies the 'kotlin-parcelize' plugin, which is useful for automatically generating Parcelable implementations for Kotlin classes. ```gradle plugins { id("kotlin-parcelize") } ``` -------------------------------- ### Get Local Device API Source: https://developer.samsung.com/health/android/data/api-reference/com/samsung/android/sdk/healthdata/HealthDeviceManager Gets a `HealthDevice` object of the current device where Samsung Health is installed. ```APIDOC ## GET /getLocalDevice ### Description Gets a `HealthDevice` object representing the current device where the Samsung Health application is installed. This is useful for identifying the primary device associated with the user's data. ### Method GET ### Endpoint `/getLocalDevice` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```java HealthDevice localDevice = healthDeviceManager.getLocalDevice(); ``` ### Response #### Success Response (200) - **HealthDevice** - The `HealthDevice` object of the current device. #### Response Example ```json { "uuid": "local-device-uuid", "name": "My Phone", "model": "Samsung Galaxy S21", "manufacturer": "Samsung" } ``` ### Errors - **IllegalStateException**: If the connection to the health data store is invalid or a remote-invocation error occurs on the connection. ``` -------------------------------- ### HealthData Constructor and Methods Source: https://developer.samsung.com/health/android/data/api-reference/com/samsung/android/sdk/healthdata/HealthData Details the HealthData class, including its constructor and various methods for getting and setting health data properties. ```APIDOC ## HealthData Class ### Description Provides a structure for holding health data, allowing for the retrieval and insertion of various data types. ### Constructor #### HealthData() Creates a health data instance. ### Methods #### getUuid Gets the unique ID of the object. ##### Parameters None ##### Returns - `String`: The unique ID contained in the object. ##### Throws - `UnsupportedOperationException`: If the health data is in `HealthDataResolver.AggregateResult` or `HealthDataResolver.ReadResult`. #### getSourceDevice Gets the source device which provides health data. ##### Parameters None ##### Returns - `String`: The ID of the source device which provides health data. #### setSourceDevice Sets the source device which provides health data. It's mandatory to set the source device for created health data. ##### Parameters - `deviceUuid` (String) - Required - The source device ID which provides health data. #### getString Gets a text value associated with a given property. ##### Parameters - `key` (String) - Required - The specific property name of health data that its value type is text. E.g. `HealthConstants.Exercise.COMMENT`. ##### Returns - `String`: The text value, or `null` if the health data object does not have the given property. #### getFloat Gets a float value associated with a given property. ##### Parameters - `key` (String) - Required - The specific property name of health data that its value type is float. E.g. `HealthConstants.Exercise.DISTANCE`. ##### Returns - `float`: The float value, or `0.0f` if the health data object does not have the given property. #### getDouble Gets a double value associated with a given property. ##### Parameters - `key` (String) - Required - The specific property name of health data that its value type is double. ##### Returns - `double`: The double value, or `0.0d` if the desired type does not exist for the given property. #### getLong Gets a long value associated with a given property. ##### Parameters - `key` (String) - Required - The specific property name of health data that its value type is long. E.g. `HealthConstants.Exercise.DURATION`. ##### Returns - `long`: The long value, or `0L` if the desired type does not exist for the given property. #### getInt Gets an integer value associated with a given property. ##### Parameters - `key` (String) - Required - The specific property name of health data that its value type is integer. ##### Returns - `int`: The integer value, or `0` if the desired type does not exist for the given property. #### clear Clears values of all properties in the health data object. ##### Parameters None #### getBlob Gets a BLOB value associated with a given property. ##### Parameters - `key` (String) - Required - The specific property name of health data that its value type is BLOB. ##### Returns - `byte[]`: The BLOB value, or `null` if the health data object does not have the given property. #### getInputStream Gets an InputStream associated with a given property. ##### Parameters - `key` (String) - Required - The specific property name of health data that its value type is InputStream. ##### Returns - `InputStream`: The InputStream associated with the property, or `null` if the property does not exist. #### putBlob Inserts a BLOB value into a given property of the health data object. ##### Parameters - `key` (String) - Required - The property name. - `value` (byte[]) - Required - The BLOB value to insert. #### putDouble Puts a double value into the given property of the health data object. ##### Parameters - `key` (String) - Required - The property name. - `value` (double) - Required - The double value to insert. #### putFloat Puts a float value into a given property of the health data object. ##### Parameters - `key` (String) - Required - The property name. - `value` (float) - Required - The float value to insert. #### putInputStream Inserts an InputStream into a given property of the health data object. ##### Parameters - `key` (String) - Required - The property name. - `value` (InputStream) - Required - The InputStream value to insert. #### putInt Puts an integer value into a given property of the health data object. ##### Parameters - `key` (String) - Required - The property name. - `value` (int) - Required - The integer value to insert. #### putLong Puts a long value into a given property of the health data object. ##### Parameters - `key` (String) - Required - The property name. - `value` (long) - Required - The long value to insert. #### putNull Inserts a `null` value into a given property of the health data object. ##### Parameters - `key` (String) - Required - The property name. #### putString Puts a text value into a given property of the health data object. ##### Parameters - `key` (String) - Required - The property name. - `value` (String) - Required - The text value to insert. ``` -------------------------------- ### Get Sleep Data Source Device Information (HealthDataResolver) Source: https://developer.samsung.com/health/android/migration-guide/overview Retrieves information about the device that provided sleep data using HealthDataResolver. ```APIDOC ## GET /sleep/source/device ### Description Retrieves the source device information for sleep data using the HealthDataResolver API. ### Method GET ### Endpoint /sleep/source/device ### Parameters #### Path Parameters None #### Query Parameters - **sortOrder** (String) - Optional. The sort order for sleep data, e.g., 'DESC' for descending by start time. - **limit** (Integer) - Optional. The maximum number of results to return. #### Request Body None ### Request Example ```json { "message": "Request to get sleep data source device information" } ``` ### Response #### Success Response (200) - **deviceId** (String) - The unique identifier of the device. - **deviceName** (String) - The custom name of the device. - **deviceType** (String) - The type or group of the device (e.g., "MOBILE", "EXTERNAL", "COMPANION or WATCH"). #### Response Example ```json { "deviceId": "some-device-uuid", "deviceName": "Samsung Galaxy Watch 5", "deviceType": "COMPANION or WATCH" } ``` ``` -------------------------------- ### Get Sleep Data Source Device Information (DataTypes) Source: https://developer.samsung.com/health/android/migration-guide/overview Retrieves information about the device that provided sleep data using the DataTypes API. ```APIDOC ## GET /sleep/source/device/data_types ### Description Retrieves the source device information for sleep data using the DataTypes API, which is part of the Samsung Health Data SDK. ### Method GET ### Endpoint /sleep/source/device/data_types ### Parameters #### Path Parameters None #### Query Parameters - **ordering** (String) - Optional. The ordering of the results, e.g., 'DESC' for descending. - **limit** (Integer) - Optional. The maximum number of results to return. #### Request Body None ### Request Example ```json { "message": "Request to get sleep data source device information using DataTypes API" } ``` ### Response #### Success Response (200) - **deviceId** (String) - The unique identifier of the device. - **deviceName** (String) - The name of the device. - **deviceType** (String) - The type of the device. #### Response Example ```json { "deviceId": "device-id-123", "deviceName": "My Smart Band", "deviceType": "WEARABLE" } ``` ```