ProgrammingGuide_HealthData

download ProgrammingGuide_HealthData

of 59

Transcript of ProgrammingGuide_HealthData

  • 7/24/2019 ProgrammingGuide_HealthData

    1/59Copyright Samsung Electronics, Co., Ltd. All rights reserved.

    Programming Guide:

    Samsung Digital Health

    - Health Data

    1.0.0 beta3

  • 7/24/2019 ProgrammingGuide_HealthData

    2/59

    Samsung Digital Health - Health Data Programming Guide

    Copyright Samsung Electronics, Co., Ltd. All rights reserved. Page | 2

    1. OVERVIEW .........................................................................................................................................................4

    1.1. DATA FRAMEWORK................................................................................................................................................. 4

    1.2. ARCHITECTURE ........................................................................................................................................................ 5

    1.2.1. DATA SOURCE DEVICE ..................................................................................................................................... 5

    1.2.2. DATA FRAMEWORK ......................................................................................................................................... 5

    1.2.3. SAMSUNG DIGITAL HEALTH APPLICATION ...................................................................................................... 5

    2. DEVELOPMENT ENVIRONMENT......................................................................................................................... 11

    2.1. PREREQUISITES ..................................................................................................................................................... 11

    2.2. DOWNLOADING HEALTH DATA OF SAMSUNG DIGITAL HEALTH SDK .................................................................. 11

    2.3. TESTING YOUR APPLICATION WITH HEALTHDEVAPP ........................................................................................... 12

    2.4. PUBLISHING YOUR APPLICATION .......................................................................................................................... 13

    3. SAMSUNG DIGITAL HEALTH FUNDAMENTALS .................................................................................................... 14

    3.1. IMPORTING LIBRARY ............................................................................................................................................. 14

    3.2. HELLO SAMSUNG DIGITAL HEALTH ....................................................................................................................... 14

    4. SAMSUNG DIGITAL HEALTH FEATURES .............................................................................................................. 17

    4.1. HEALTH DATA STORE ............................................................................................................................................ 17

    4.1.1. CONNECTION TO HEALTH DATA STORE ........................................................................................................ 17

    4.1.2. SYNCHRONOUS VS ASYNCHRONOUS REQUEST ............................................................................................ 17

    4.1.3. INSERTING HEALTH DATA ............................................................................................................................. 19

    4.1.4. READING HEALTH DATA ................................................................................................................................ 20

    4.1.5. FILTER ............................................................................................................................................................ 20

    4.1.6. UPDATING HEALTH DATA.............................................................................................................................. 21

    4.1.7. DELETING HEALTH DATA ............................................................................................................................... 21

    4.1.8. AGGREGATION .............................................................................................................................................. 22

    4.1.9. DATA NORMALIZATION ................................................................................................................................. 22

    4.2. HEALTH DATA TYPE ............................................................................................................................................... 23

    4.3. PRIVACY ................................................................................................................................................................. 28

    5. USE CASES ........................................................................................................................................................ 29

    5.1. CONNECTING TO HEALTHDATASTORE .................................................................................................................. 29

    5.2. ACQUIRING USER PERMISSION ............................................................................................................................. 30

    5.3. INSERTING DATA ................................................................................................................................................... 32

    5.4. UPDATING DATA ................................................................................................................................................... 34

    5.5. DELETING DATA ..................................................................................................................................................... 35

    5.6. READING DATA ...................................................................................................................................................... 37

    5.7. AGGREGATING DATA ............................................................................................................................................ 385.8. OBSERVING CHANGE ............................................................................................................................................. 40

    6. SAMPLE APPLICATIONS ..................................................................................................................................... 41

    6.1. SIMPLEHEALTH ...................................................................................................................................................... 41

    6.1.1. MAINACTIVITY ............................................................................................................................................... 42

    6.1.2. STEPCOUNTREPORTER .................................................................................................................................. 44

    6.2. FOODNOTE ............................................................................................................................................................ 46

    6.2.1. MAINACTIVITY ............................................................................................................................................... 48

    6.2.2. CHOOSEFOODACTIVITY ................................................................................................................................. 50

    6.2.3. MEALSTOREACTIVITY .................................................................................................................................... 51

    Table of Contents

  • 7/24/2019 ProgrammingGuide_HealthData

    3/59

    Samsung Digital Health - Health Data Programming Guide

    Copyright Samsung Electronics, Co., Ltd. All rights reserved. Page | 3

    6.2.4. FOODDATAHELPER ........................................................................................................................................ 52

    APPENDIX A. HEALTHDEVAPP - IMPORT DATA ..................................................................................................... 57

    APPENDIX B. HEALTHDEVAPP - EXPORT DATA ..................................................................................................... 58

    COPYRIGHT .............................................................................................................................................................. 59

  • 7/24/2019 ProgrammingGuide_HealthData

    4/59

    Samsung Digital Health - Health Data Programming Guide

    Copyright Samsung Electronics, Co., Ltd. All rights reserved. Page | 4

    1.

    Overview

    Health is a main keyword nowadays and related services are increasing continuously with the need for health

    improvement. Samsung Digital Health SDK helps developers to make useful health applications that handle health

    data safely, and share health data with other applications based on users consent.

    Figure 1: Samsung Digital Health service

    Refer toTable 1 for Samsung Digital Health SDK glossary.

    Term Description

    Data Framework It provides useful features to handle users health data. As it is included in S Health,

    applications for Samsung Digital Health works after installing S Health.

    S Health An application that helps that monitors users activities and helps user makes a healthier life

    with pedometer, exercise, heart rate, and etc.

    Its written as italicin this document.

    Table 1: Glossary

    1.1.

    Data Framework

    The Data Framework of Samsung Digital Health SDK provides the following features:

    -

    Health Data Store

    Handling the connection state

    Inserting, reading, updating, deleting health data

    Unified unit conversion

    -

    Health Data Type

    Platform-defined data type

  • 7/24/2019 ProgrammingGuide_HealthData

    5/59

    Samsung Digital Health - Health Data Programming Guide

    Copyright Samsung Electronics, Co., Ltd. All rights reserved. Page | 5

    -

    Privacy

    Granting permission based on users consent to read or write the specific data type

    1.2.

    Architecture

    The Data Framework of Samsung Digital Health is designed to provide safe access for health data and a seamlesshealth service to user.Figure 2 is the architecture for the Data Framework of Samsung Digital Health.

    Figure 2: Architecture for the Data Framework of Samsung Digital Health

    The detailed description is presented below.

    1.2.1.

    Data Source Device

    Devices that have various sensors such as the pedometer, accelerator, or heart rate sensor can measure health data

    of user. We call the device that provides health data of user as the source device and each health data that handled

    in the Data Framework has source device information.

    1.2.2.

    Data Framework

    The Data Framework is the nub for the Samsung Digital Health service. It keeps users health data safely with variousdata types based on XML schema definition. Health data coming from a specific source device is inserted with the

    unified data unit, read, updated, or deleted through the data store connection through the Data Framework. As it is

    included in the S Health,applications need to install S Health.

    1.2.3.

    Samsung Digital Health Application

    A Samsung Digital Health application indicates an application that uses the Data Framework of Samsung Digital

    Health. Samsung Digital Health SDK provides HealthDevAppthat enables you to substitute S Health. It helps you to

  • 7/24/2019 ProgrammingGuide_HealthData

    6/59

    Samsung Digital Health - Health Data Programming Guide

    Copyright Samsung Electronics, Co., Ltd. All rights reserved. Page | 6

    develop applications even if S Healthis not installed in the device. You c and find it in the [samsung-digital-health-healthdata]\Toolsfolder.

    Figure 3 shows the relationship between classes and interfaces of the com.samsung.android.sdk.healthdatapackage. Detailed descriptions for each class and interface are in the API Reference under the[samsung-digital-health-healthdata]\Docs\API Referencefolder.

    HealthDataServiceinitializes the Health data service. APIs of thecom.samsung.android.sdk.healthdataworks properly after initialize() is called without an exception.

    HealthDataStorehandles the connection to the data storage of the device. It receives its connection result withHealthDataStore.ConnectionLsitener. Most requests require the connection to the health data store.

    The Data Framework provides classes and interface to insert, read, update, or delete health data.

    HealthDataResolveris a central class to handle health data. It sends a data request with related requestinterfaces and gets a result through HealthResultHolder . The result can be received immediately withHealthDataHolder.BaseResult, HealthDataResolver.ReadResultorHealthDataResolver.AggregateResult. Or it can be received asynchronously with

    HealthResultHolder.ResultListener. See4.1 for more information.

  • 7/24/2019 ProgrammingGuide_HealthData

    7/59

    Samsung Digital Health - Health Data Programming Guide

    Copyright Samsung Electronics, Co., Ltd. All rights reserved. Page | 7

    Figure 3: Class diagram related to HealthDataStore

    HealthDataStore

    HealthDataResolver HealthDataResolver.Filter

    HealthDataResolver.ReadRequest

    HealthDataResolver.ReadRequest.Builder

    HealthDataRes olver.InsertRequest .Builder

    HealthDataResolver.InsertRequest

    HealthDataResolver.UpdateRequest.Builder

    HealthDataResolver.UpdateRequest

    HealthDataResolver.DeleteRequest

    HealthDataRes olver.DeleteRequest.Builder

    HealthResultHolder.ResultListener

    HealthResultHolder.BaseResult

    HealthDataResolver.ReadResult

    HealthDataResolver.AggregateResult

    HealthResultHolder

    HealthDataResolver.AggregateRequest

    HealthDataResolver.AggregateRequest.Builder

    HealthDataStore.ConnectionListener

    HealthData

    HealthDeviceManager

    HealthDevice

    HealthDevice.Builder

    HealthDataService

    +initialize()

  • 7/24/2019 ProgrammingGuide_HealthData

    8/59

    Samsung Digital Health - Health Data Programming Guide

    Copyright Samsung Electronics, Co., Ltd. All rights reserved. Page | 8

    Application developers can use platform-defined data types that Samsung Digital Health provides. See4.2 for more

    information. Especially HealthConstants.Common contains the following mandatory properties for health data.

    -

    Unique ID of health data

    -

    Created and updated time of health data

    -

    Application package name

    -

    Device that provides health data

    HealthConstants.Commonis the base class of predefined data types of Samsung Digital Health as inFigure 4.

    Figure 4: Class diagram related to health data type

  • 7/24/2019 ProgrammingGuide_HealthData

    9/59

    Samsung Digital Health - Health Data Programming Guide

    Copyright Samsung Electronics, Co., Ltd. All rights reserved. Page | 9

    Users health data can be accessed with the users consent.Figure 5 shows relationship between classes and

    interface related toHealthPermissionManager. It requests permissions withHealthPermissionManager.PermissionKeythat contains the required permission to read or write for thespecific health data type. The permission result can be received synchronous or asynchronously. See4.3 for more

    information.

    Figure 5: Class diagram related to HealthPermissionManager

    The Health Data library of Samsung Digital Health provides the following package:

    - com.samsung.android.sdk.healthdata

    Main interfaces and classes in the library are described inTable 2.See the API reference on details.

    com.samsung.android.sdk.healthdata

    Interface / Class Description

    HealthConnectionErrorResult This class handles errors for connection failure to the health data store.

    HealthConstants This class defines constants of health data and contains interfaces for various kinds ofhealth data such as the count of steps or exercise.

    HealthData This class is an object for a health data type, e.g., the blood pressure or weight.Quantitative and qualitative values can be specified for the specific health data type

    based on its data structure definition. It is used to manage health data withHealthDataResolver.

    HealthDataObserver This class defines an observer to handle health data changes.

    HealthDataResolver This class accesses health data to insert, read, update, and delete with the filter andaggregate functions.

    HealthDataService This class initializes the Health data service.

    HealthDataStore This class handles the connection to the data store in the device.

    HealthDataUnit This class provides unified units for the health data store.

    HealthDataStore HealthPermissionManager

    HealthDataStore.ConnectionListener

    HealthPermissionManager.PermissionKey

    HealthPermissionManager.PermissionType

    HealthPermissionManager.PermissionResult

    HealthResultHolder.ResultListener

    HealthResultHolder.BaseResult

    HealthResultHolder

  • 7/24/2019 ProgrammingGuide_HealthData

    10/59

    Samsung Digital Health - Health Data Programming Guide

    Copyright Samsung Electronics, Co., Ltd. All rights reserved. Page | 10

    HealthDevice This class contains detailed device information that provides health data.

    HeatlthDeviceManager This class manages devices related health data.

    HealthPermissionManager This class requests permission to read or write health data for the specific health datatype.

    HealthResultHolder This interface represents the result of invoking method.

    HealthUserProfile This class provides user information.

    Table 2: Interfaces and classes of com.samsung.android.sdk.healthdata

  • 7/24/2019 ProgrammingGuide_HealthData

    11/59

    Samsung Digital Health - Health Data Programming Guide

    Copyright Samsung Electronics, Co., Ltd. All rights reserved. Page | 11

    2.

    Development Environment

    To develop applications with Samsung Digital Health features, check prerequisites for the SDK first.

    2.1.Prerequisites

    Before downloading Samsung Digital Health SDK, refer to the following information.

    Android Version

    Android 4.4 KitKat (API level 19) or above

    Available Devices

    Samsung Android devices (KitKat or above)

    2.2.

    Downloading Health Data of Samsung Digital Health SDK

    Samsung Digital Health SDK can be downloaded in the Samsung developer site. If the downloaded SDK is unzipped,

    you can check the following content inTable 3 for the application development.

    Folder in SDK Description

    Docs API Reference

    Describes Samsung Digital Health APIs

    Programming Guide

    Contains development information to create Samsung Digital Health applications

    Libs samsung-digital-health-healthdata-v1.0.0.jar

    Client library of Samsung Digital Health SDK

    sdk-v1.0.0.jar

    Basic library for the Samsung SDK

    Samples SimpleHealth

    Sample application that demonstrates how to use Samsung Digital Health SDK

    FoodNote

    Sample application to check daily calorie intake

    Tools HealthDevApp.apk

    An application to substitute S Health. Itprovides the Samsung Digital Health service on the

    development phase.

    DataImportSample-Weight.csv/txt

    Example files to import health data with HealthDevApp

    Table 3: Samsung Digital Health SDK content

  • 7/24/2019 ProgrammingGuide_HealthData

    12/59

    Samsung Digital Health - Health Data Programming Guide

    Copyright Samsung Electronics, Co., Ltd. All rights reserved. Page | 12

    2.3.

    Testing Your Application with HealthDevApp

    Samsung Digital Health SDK provides HealthDevAppas a tool for its application development. HealthDevAppenables

    applications to use the Samsung Digital Health service as a substitution for S Healthin the development phase.

    Because the available S Healthversion for the Samsung Digital Health service is not yet released, install

    HealthDevAppin the device and start to make your application.

    Figure 6: HealthDevApp

    It includes the following features.

    -

    Samsung Digital Health

    HealthDevAppprovides the Samsung Digital Health service for your application.

    -

    Dashboard

    It shows health data in the health data store with its detailed values by each data type.-

    User profile

    HealthDevAppprovides a test environment for user profile such as the name, gender, birthday, or

    height.

    -

    Pedometer

    It provides a simple way to collect health data for steps. If you check it and walk with the device,

    pedometer data is inserted to the health data store. Accumulated pedometer data can be checked in

    Step Counton Dashboard.

    -

    Permission setting

  • 7/24/2019 ProgrammingGuide_HealthData

    13/59

    Samsung Digital Health - Health Data Programming Guide

    Copyright Samsung Electronics, Co., Ltd. All rights reserved. Page | 13

    Permissions can be managed and checked for each application of permission related.

    -

    Import Data

    Importing health data with csvor txtis provided for your convenience. Health data of the file canbe inserted to the health data store. Refer toAppendix A for more information.

    -

    Export Data

    Health data in the health data store can be exported to the text orcsvfile. Refer toAppendix B formore information. Refer toAppendix B for more information.

    -

    Password

    It provides the test environment if user sets a password for health data. If the password is set, the

    health data store is not connected until the password in entered.

    Platform Type

    If you use HealthDevAppin the debugging mode, you need to add the following metadata to the

    AndroidManifest.xmlfile of your application project.

    2.4.

    Publishing Your Application

    Refer to the following guidelines to publish your application.

    Packaging Application

    If your application is ready to publish, change the value of metadata information for the health platform type to"rel" as shown below and package your application.

    If you dont change the value above, your application doesnt run with S Health.

    Request for Partner Apps

    Applications works with S Healthrun properly after the partner application registration. Because health data is

    closely connected to the privacy and medical issues, Samsung checks violations in your application and registers your

    application as the partner application after. You can request for the partner application on thedeveloper site.

    http://developer.samsung.com/healthhttp://developer.samsung.com/healthhttp://developer.samsung.com/healthhttp://developer.samsung.com/health
  • 7/24/2019 ProgrammingGuide_HealthData

    14/59

    Samsung Digital Health - Health Data Programming Guide

    Copyright Samsung Electronics, Co., Ltd. All rights reserved. Page | 14

    3.

    Samsung Digital Health Fundamentals

    If you checked prerequisites for the application development and the downloaded SDK content, its ready to start

    creating an application. The following sections give you fundamentals for developing a Samsung Digital Health

    application.

    3.1.

    Importing Library

    Add samsung-digital-health-healthdata-v1.0.0.jarand sdk-v1.0.0.jarto the libsfolder in your created applicationproject.

    3.2.

    Hello Samsung Digital Health

    The example below shows essential code for a Samsung Digital Health application.

    -

    Initializes the Health data service with HealthDataService .-

    Connects to the health data store withHealthDataStore.The other operations are available after checking the connection state in the connection callback.

    -

    Acquires the required permission to read or write users health data with HealthPermissionManager.

    importcom.samsung.android.sdk.healthdata.*;

    publicclassMainActivity extendsActivity {

    privateHealthDataStore mStore;

    private HealthPermissionManager.PermissionKey mPermissionKey;

    @Override

    publicvoidonCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    mPermissionKey= new PermissionKey(HealthConstants.StepCount.HEALTH_DATA_TYPE,

    PermissionType.READ);

    HealthDataService healthDataService = new HealthDataService();

    try{

    // Initializes the Health data service

    healthDataService.initialize( this);

    } catch(Exception e) {

    // Handles exception}

    mStore= newHealthDataStore(this, mConnectionListener);

    // Connects to the health data store

    mStore.connectService();

    }

    @OverridepublicvoidonDestroy() {

    mStore.disconnectService();super.onDestroy();

    }

  • 7/24/2019 ProgrammingGuide_HealthData

    15/59

    Samsung Digital Health - Health Data Programming Guide

    Copyright Samsung Electronics, Co., Ltd. All rights reserved. Page | 15

    privatefinal HealthDataStore.ConnectionListener mConnectionListener= newHealthDataStore.ConnectionListener() {

    @OverridepublicvoidonConnected() {

    // The connection is successful.// Acquires the required permission

    HealthPermissionManager pmsManager = newHealthPermissionManager(mStore);

    try{// Check whether the required permission is acquiredSet keySet = new HashSet();keySet.add(mPermissionKey);Map resultMap = pmsManager.isPermissionAcquired(keySet);

    if(resultMap.get(mPermissionKey) == Boolean.TRUE) {// The permission has been acquired already

    } else{// Requests permission to read the count of stepspmsManager.requestPermissions(keySet)

    .setResultListener(mPermissionListener);}

    } catch(Exception e) {// Error handling

    }}

    @OverridepublicvoidonConnectionFailed(HealthConnectionErrorResult error) {

    // Resolve error if the connection failserror.resolve(this);

    }

    @OverridepublicvoidonDisconnected() {

    // The connection is disconnected

    }};

    privatefinal HealthResultHolder.ResultListener mPermissionListener=newHealthResultHolder.ResultListener() {

    @OverridepublicvoidonResult(PermissionResult result) {

    Map resultMap = result.getResultMap();

    if(resultMap.get(mPermissionKey) == Boolean.FALSE) {// The requested permission is not acquired

    } else{// The requested permission is acquired.

    }

    }};

    }

    Figure 7 show an activity for resolve()if the connection to the health data store fails. If it is caused byOLD_VERSION_PLATFORM, the activity needs to download the latest S Health. If it is caused by OLD_VERSION_SDK,its required to download the latest version of your application.

  • 7/24/2019 ProgrammingGuide_HealthData

    16/59

    Samsung Digital Health - Health Data Programming Guide

    Copyright Samsung Electronics, Co., Ltd. All rights reserved. Page | 16

    Figure 7: Activity for resolve()

  • 7/24/2019 ProgrammingGuide_HealthData

    17/59

    Samsung Digital Health - Health Data Programming Guide

    Copyright Samsung Electronics, Co., Ltd. All rights reserved. Page | 17

    4.

    Samsung Digital Health Features

    Key features of Samsung Digital Health SDK are:

    -

    Health data store

    -

    Health data types

    -

    Privacy

    4.1.Health Data Store

    Samsung Digital Health SDK provides the health data store to access health data with users consent. The data access

    includes inserting, reading, updating, and deleting health data. Data in the health data store can be shared among

    applications.

    4.1.1.

    Connection to Health Data Store

    The connection to the health data store is required to access health data in the health data store.

    HealthDataStoreprovides connectService() and disconnectService()and its events can be checked withHealthDataStore.ConnectionListener. See5.1 for its use case.

    4.1.2.

    Synchronous vs Asynchronous Request

    Data can be accessed with the following APIs of HealthDataResolver . It enables an application to request thefollowing operations.

    -

    HealthResultHolder insert(InsertRequest request)

    - HealthResultHolder update(UpdateRequest request)

    -

    HealthResultHolder delete(DeleteRequest request)

    - HealthResultHolder read(ReadRequest request)

    -

    HealthResultHolder aggregate(AggregateRequest request)

    Its result is received throughHealthResultHolderas a container for the corresponding result. The result ofHealthDataResolver.ReadResultand HealthDataResolver.AggregateResultare returned as theCursorinterface. You can check the data value by moving the cursor.

    The result of the health data request can be received either synchronously or asynchronously. You can choose one of

    them for your application design.

    If you want to get the result immediately for the health data request, useHealthResultHolder.await() asshown below. It throws an exception if it is called in the main thread.

    importcom.samsung.android.sdk.healthdata.*;

    // The state of connectionprivateHealthDataStore mStore;

    privatevoidreadGlucoseSynchronously(longstart, longend) {

  • 7/24/2019 ProgrammingGuide_HealthData

    18/59

    Samsung Digital Health - Health Data Programming Guide

    Copyright Samsung Electronics, Co., Ltd. All rights reserved. Page | 18

    HealthDataResolver resolver = new HealthDataResolver(mStore, null);

    Filter filter = Filter.greaterThan(HealthConstants.BloodGlucose.GLUCOSE, 125);ReadRequest request = newReadRequest.Builder()

    .setDataType(HealthConstants.BloodGlucose.HEALTH_DATA_TYPE)

    .setFilter(filter)

    .build();

    try{// Checks the result immediately// It has to be called in another thread from the main threadReadResult c = resolver.read(request).await()

    if(c != null) {List dataList = newArrayList();

    while(c.moveToNext()) {floatdata = c.getFloat(c.getColumnIndex(HealthConstants.BloodGlucose.GLUCOSE));dataList.add(data);

    }c.close();

    }else{

    Log.d(APP_TAG, "There is no result.");}

    } catch(Exception e) {Log.d(APP_TAG, "Reading health data fails.");

    }}

    If you need to request asynchronously, set the result listener with

    HealthResultHolder.setResultListener().

    An example below shows the asynchronous request.

    importcom.samsung.android.sdk.healthdata.*;

    // The state of connectionprivateHealthDataStore mStore;

    privatevoid readGlucoseAsynchronously(longstart, longend) {HealthDataResolver resolver = new HealthDataResolver(mStore, null);

    Filter filter = Filter.greaterThan(HealthConstants.BloodGlucose.GLUCOSE, 125);ReadRequest request = newReadRequest.Builder()

    .setDataType(HealthConstants.BloodGlucose.HEALTH_DATA_TYPE)

    .setFilter(filter)

    .build();

    try{resolver.read(request).setResultListener(newHealthResultHolder.ResultListener() {

    @OverridepublicvoidonResult(ReadResult result) {

    // Checks the resultCursor c = result.getResultCursor();

    if(c != null) {List dataList = newArrayList();

    while(c.moveToNext()) {floatdata = c.getFloat(c.getColumnIndex(HealthConstants.BloodGlucose.GLUCOSE));dataList.add(data);

  • 7/24/2019 ProgrammingGuide_HealthData

    19/59

    Samsung Digital Health - Health Data Programming Guide

    Copyright Samsung Electronics, Co., Ltd. All rights reserved. Page | 19

    }c.close();

    }else{

    Log.d(APP_TAG, "There is no result.");}

    }};

    } catch(Exception e) {Log.d(APP_TAG, "Reading health data fails.");}

    }

    4.1.3.

    Inserting Health Data

    The Data Framework enables your application to add created health data for the specific data type. Each data to be

    added needs to specify the following information.

    -

    Data type

    -

    Source device ID that provides health data-

    Health data including mandatory properties that are defined in the data type.

    See4.2 on details for health data properties of the health data type.

    The Data Framework registers the current device where your application is installed. If the source device is the

    current device, its ID can be checked as shown below.

    importcom.samsung.android.sdk.healthdata.*;

    // The state of connectionprivateHealthDataStore mStore;

    privatevoidgetCurrentDeviceInfo() {

    HealthDeviceManager deviceManager = newHealthDeviceManager(mStore);HealthDevice device = deviceManager.getLocalDevice();String devicdId = device.getUuid();

    }

    You can register more source devices withHealthDevice.Builder.build()andHealthDeviceManager.regsiterDevice().

    importcom.samsung.android.sdk.healthdata.*;

    // The state of connectionprivateHealthDataStore mStore;

    privatevoidregisterDevice(String seed, String manufacturer, String model) {// Specifies device informationHealthDevice.Builder builder = newHealthDevice.Builder();HealthDevice device = builder.setModel(model)

    .setManufacturer("Samsung")

    .setDeviceSeed("400E85A7ED28")

    .setGroup(HealthDevice.GROUP_MOBILE )

    .build();

    // Registers the deviceHealthDeviceManager deviceManager = newHealthDeviceManager(mStore);try{

  • 7/24/2019 ProgrammingGuide_HealthData

    20/59

    Samsung Digital Health - Health Data Programming Guide

    Copyright Samsung Electronics, Co., Ltd. All rights reserved. Page | 20

    deviceManager.registerDevice(device);} catch{

    // Error handling}

    }

    When you insert health data to the health data store, check units of data values are correct. Get more information

    from4.1.9.

    The health data store accepts only validated health data. If any mandatory property is missing,

    HealthDataResolver.insert() throws an exception. If property values dont satisfy the validation range, it succeeds but

    inserted values are ignored.

    You can check the number of data with BaseResult.getCount() in the result of HealthDataResolver.insert(). The size

    limitation for blob type insertion is 1 megabyte.

    4.1.4.

    Reading Health Data

    An application can read health data for the specific data type through the health data store. More conditions can beadded to HealthResolve.ReadRequestto get required data.

    -

    Filter if a condition for the property of the data type is required

    -

    Properties and property alias of the result

    -

    Sort order of the result

    -

    Source device if a condition for source devices that provides health data is required

    -

    Package name if a condition for the package name that provides health data is required

    4.1.5.

    Filter

    HealthDataResolver.Filteris very useful to clear the data range for reading, updating, and aggregating healthdata. Each filter contains one comparison below.

    -

    eq()

    - greaterThan()

    -

    greaterThanEquals()

    -

    in()

    -

    lessThan()

    -

    lessThanEquals()

    - not()

    Multiple filters can be combined with and()and or()asFigure 8 and example below.

  • 7/24/2019 ProgrammingGuide_HealthData

    21/59

    Samsung Digital Health - Health Data Programming Guide

    Copyright Samsung Electronics, Co., Ltd. All rights reserved. Page | 21

    Figure 8: Using filter

    importcom.samsung.android.sdk.healthdata.*;

    Filter filter1 = Filter.eq("property1", "AAA");Filter filter2 = Filter.eq("property2", "BBB");Filter filter3 = Filter.greaterThanEquals("property3",100);

    Filter filter = Filter.and(Filter.or(filter1, filter2), filter3);

    If all three filters above need to be combined withand(), refer to the following example.

    Filter badFilterEx = Filter.and(Filter.and(filter1, filter2), filter3); // Bad example for Filter

    Filter goodFilterEx = Filter.and(filter1, filter2, filter3); // Good example for Filter

    If you want to make a filter for the specific property, refer to the following example.

    Filter badFilterEx = Filter.or( // Bad example for FilterFilter.eq("Property1", "AAA"),Filter.eq("Property1", "BBB"),

    Filter.eq("Property1", "CCC"));

    Filter goodFilterEx = Filter.in("Property1", {"AAA", "BBB", "CCC"}); // Good example for Filter

    4.1.6.Updating Health Data

    HealthResolve.UpdateRequestenables you to update specific health data of the specific data type. Only healthdata that is inserted by your application can be updated. See required information below to update health data.

    -

    Data type

    -

    Health data that includes values for the specific properties to be updated

    -

    Filter to set the specific range to update

    4.1.7.

    Deleting Health Data

    Health data deletion is available with HealthResolve.DeleteRequest. Only health data that is inserted by yourapplication can be deleted. It requires following information.

  • 7/24/2019 ProgrammingGuide_HealthData

    22/59

    Samsung Digital Health - Health Data Programming Guide

    Copyright Samsung Electronics, Co., Ltd. All rights reserved. Page | 22

    -

    Data type

    -

    Unique IDs for health data to be deleted

    If you want to specify the data range more, set a filter to DeleteRequest. Data IDs of the result can be used todelete data.

    4.1.8.

    Aggregation

    The Data Framework provides useful aggregate functions to get statistical information. Available aggregate functions

    are:

    - SUM

    - COUNT

    - AVG

    -

    MIN

    - MAX

    You can add a group for the specific property of the data type with alias that make easy to figure the result value out

    Especially a time group with the specific time unit can be specified with

    HealthDataResolver.Aggregate.TimeGroupUnit. Available time units and the value formation for each timeunit in the result are described inTable 4.

    Unit Value format in the result

    Minutelyyyyy-mm-dd hh:mm

    (e.g. 2014-10-09 18:17)

    Hourlyyyyy-mm-dd hh

    (e.g. 2014-10-09 18)

    Dailyyyyy-mm-dd

    (e.g. 2014-10-09)

    Weeklyyyyy-ww

    (e.g. 2014-41)

    Monthlyyyyy-mm

    (e.g. 2014-10)

    Table 4: Time unit and the value format in the result

    If you add a time unit group with Hourlyas "hour" alias, the result for the aggregate request contains an "hour"

    property with "yyyy-mm-dd hh" formatted values if the request is successful.

    4.1.9.Data Normalization

    The health data is stored based on the normalized unit as defined in International System of Unit (SI) inTable 6.

    Item Unit Item Unit

    Height cm Calorie Kcal

    Weight Kg Sp3ed m/h

  • 7/24/2019 ProgrammingGuide_HealthData

    23/59

    Samsung Digital Health - Health Data Programming Guide

    Copyright Samsung Electronics, Co., Ltd. All rights reserved. Page | 23

    Temperature Celsius Fat, visceral fat Kg

    Distance Meter Muscle mass Kg

    Blood glucose mmol Bone mass Kg

    HbA1c % Time Millisecond

    Blood Pressure mmHg Body water Liter

    Table 5: International System of Unit

    It enables your application to read health data without the specific unit. It means that you need to be careful to unify

    the data units when you insert health data to the health data store. HealthDataUnit helps to convert data valuebetween units.

    If there is no required unit in HealthDataUnit, you can define and register a new unit as shown below.

    importcom.samsung.android.sdk.healthdata.*;public class HealthDataUnitExample {

    publicstaticfinalCustomUnit CUSTOM= newCustomUnit();

    voidconvertToCustom() {CustomUnit unit = newCustomUnit();HealthDataUnit.registerDataUnit(unit);

    doublecustom = CUSTOM.convertTo(1.0d, HealthDataUnit.METER);}

    publicstaticclassCustomUnit extendsHealthDataUnit {CustomUnit() {

    mUnit= "custom";}

    @Override

    publicdoubleconvertTo(doublesource, HealthDataUnit unit) {finalString unitString = unit.getUnitName();if(unitString.equalsIgnoreCase("m")) {

    returnsource * 2;}thrownewUnknownFormatConversionException("No conversion is defined");

    }}

    }

    4.2.

    Health Data Type

    Samsung Digital Health SDK provides useful predefined data types. Predefined data types of Samsung Digital HealthSDK are inTable 6.

    Name Description

    HealthConstants.Weight Historical records of user's weight

    HealthConstants.BloodGlucose The amount of glucose (sugar) present in blood

    HealthConstants.HbA1c Glycated hemoglobin data

    HealthConstants.BloodPressureThe pressure exerted by circulating blood upon walls of blood

    vessels

  • 7/24/2019 ProgrammingGuide_HealthData

    24/59

    Samsung Digital Health - Health Data Programming Guide

    Copyright Samsung Electronics, Co., Ltd. All rights reserved. Page | 24

    HealthConstants.BodyTemperatureBody temperature of user, known as normothermia or

    euthermia

    HealthConstants.HeartRate Measured heart rate values represented in beats per minute

    HealthConstants.Electrocardiogram Electrical activity of the heart over a period of time

    HealthConstants.OxygenSaturation The oxygen saturation value of user

    HealthConstants.StepCount Accumulative count of steps over a short period of time(binning)

    HealthConstants.Sleep Information about user sleep

    HealthConstants.AmbientTemperature Ambient temperature and humidity data around device

    HealthConstants.UvExposure Degree of exposure to ultraviolet(UV) radiated from the sun

    HealthConstants.Exercise Whole workout that user does for enhancing fitness and health

    HealthConstants.WaterIntake Records about how much and many times user takes water

    HealthConstants.CaffeinIntake Amount of caffeine intake

    HealthConstants.FoodInfo Set of particular food information such as nutrition and calorie

    HealthConstants.FoodIntake Records about how much user takes food and calories

    Table 6: Predefined data types

    All data types have the following mandatory properties inTable 7.

    Property Description

    UUIDID of health data.

    Assigned by the system.

    CREATED_TIME

    UTC time when data is created.

    Assigned by the system.

    UPDATED_TIMEUTC time when data is updated.

    Assigned by the system.

    PACKAGE_NAMEApplication package name which provides data.

    Assigned by the system.

    DEVICE_UUID Device ID which provides health data

    Table 7: Mandatory properties of health data

    The manifest for the data type is composed of meta-data to present characteristics of the health data type. It is

    defined as the XML schema.Table 8 shows each element description for the manifest.

    Element Description

    Base elementfor the data type. Its attributes are shown below.

    - "id"

    Data type ID

    - "import"

    Indicates another "id"of another manifest to extend

  • 7/24/2019 ProgrammingGuide_HealthData

    25/59

  • 7/24/2019 ProgrammingGuide_HealthData

    26/59

    Samsung Digital Health - Health Data Programming Guide

    Copyright Samsung Electronics, Co., Ltd. All rights reserved. Page | 26

    -

    "allowed"

    "yes": If all allowed counties are written.

    "no": If all prohibited countries are written.

    - Allowed or prohibited country codes with two-letter uppercase as defined byISO 3166-1.

    Use comma "," as the delimiter between country codes.

    E.g.

    AO, GB, IE

    Defines detailed information for each property of this data type including the default value,validation range, title and description. Its attributes are shown below.

    - "name"

    - "type"

    One of "int", "long", "float", "double", "text", and "blob"

    - "mandatory"

    The default value is "no".

    "yes" if the property is a mandatory property for the data type. Be careful not to make the

    property as "yes" if you add a new property to update your application.

    If the property is defined as mandatory, the value for the property has to be specified when

    new data is inserted.

    - "unique"

    The default value is "no".

    "yes" if the data value needs to be unique

    Default value of the property to be filled when a new health data is inserted without value

    specification

    Validation range

    - "min"

    The minimum value if the type is numeric

    - "max"

    The maximum value if the type is numeric

    - "minLength"

    The minimum length if the type is text

    - "maxLength"

    The maximum length if the type is text

    Description for the property of the data type.

    Table 8: Manifest definition

    An example below shows the manifest definition for the health data type.

    http://en.wikipedia.org/wiki/ISO_3166-1http://en.wikipedia.org/wiki/ISO_3166-1http://en.wikipedia.org/wiki/ISO_3166-1http://en.wikipedia.org/wiki/ISO_3166-1
  • 7/24/2019 ProgrammingGuide_HealthData

    27/59

    Samsung Digital Health - Health Data Programming Guide

    Copyright Samsung Electronics, Co., Ltd. All rights reserved. Page | 27

    01234567

    8910111213141516171819202122

    2324252627282930313233343536

    373839

    Blood GlucoseGlucosa en la sangre

    AO, GB, IE, FR, NL, BE, LU, AT, SK, GR, CY, SI, DZ, IR, CA,KR

    Unique IDUnique ID

    ...

    Start timeWhen the measurement was taken

    Time offsetTime zone in which data is entered

    ...

    Its detailed description is as follows.

    -

    Line 1: manifest schema version

    -

    Line 2: data type ID

    -

    Line 5-8: documentation for this data type

    Line 6: data type name with the default language attribute

    Line 7: data type name with the specific language attribute-

    Line 9: visibility of this data type

    -

    Line 10-16: data policy with its lifetime, measurement type, privacy level

    Line 14: Prohibited country codes

    -

    Line 18-39: property definition

    Line 18: Name, mandatory option, data type, and unique option for the property

    Line 18: validation range of value

    Line 19: Property description

    http://schemas.samsung.com/2014/10/iothttp://schemas.samsung.com/2014/10/iothttp://schemas.samsung.com/2014/10/iothttp://schemas.samsung.com/2014/10/iot
  • 7/24/2019 ProgrammingGuide_HealthData

    28/59

    Samsung Digital Health - Health Data Programming Guide

    Copyright Samsung Electronics, Co., Ltd. All rights reserved. Page | 28

    4.3.

    Privacy

    Privacy is a key for handling health data. Samsung Digital Health enables your application to access health data based

    on users consent. An application needs to declare proper permissions for handling required health data types and to

    handle SecureExceptionwhen the application cannot gain user consent because user can withdraw consent atany time. See5.2 on details for permission declaration.

    Declared permissions in manifest can be checked in the user permission menu ofSettingsof S Healthor applications

    as inFigure 9.The permission menu shows declared all the data types and user may change permission for each data

    type at any time. When a permission API is called in an application, the Data Framework shows permissions related

    to the requested permission API only. The flow can be preceded after user approves or denies the data type usage.

    User consent is limited to the device. Even if multiple devices use the same Samsung account, the application has to

    acquire user consent on each device independently.

    Figure 9: Privacy and user permission

  • 7/24/2019 ProgrammingGuide_HealthData

    29/59

    Samsung Digital Health - Health Data Programming Guide

    Copyright Samsung Electronics, Co., Ltd. All rights reserved. Page | 29

    5.

    Use Cases

    Useful examples to develop an application are as follows.

    -

    Connecting to HealthDataStore

    -

    Acquiring user permission

    -

    Inserting data

    -

    Updating data

    -

    Deleting data

    -

    Reading data

    -

    Aggregating data

    -

    Observing change

    5.1.

    Connecting to HealthDataStoreAn application has to connect to HealthDataStoreto handle health data. Other APIs work after the health datastore is connected successfully. Its sequence is shown below.

    1)

    Implement the HealthDataStore.ConnectionListener interface.

    2)

    Create a HealthDataStoreinstance.

    3)

    Call connectService() to connect to health service.

    4)

    After receiving the onConnected()callback, other APIs work properly.

    Figure 10: Sequence diagram for connecting to health data store

    Its example code is shown below.

    : Application

    : HealthDataStore: ConnectionListener

    1

    2

    3 : connectService()

    4 : onConnected()

  • 7/24/2019 ProgrammingGuide_HealthData

    30/59

    Samsung Digital Health - Health Data Programming Guide

    Copyright Samsung Electronics, Co., Ltd. All rights reserved. Page | 30

    import com.samsung.android.sdk.healthdata. *;

    publicclassMainActivity extendsActivity {privateHealthDataStore mStore;

    @OverridepublicvoidonCreate(Bundle savedInstanceState) {

    HealthDataService healthDataService = new HealthDataService();

    try{healthDataService.initialize( this);

    } catch(Exception e) {

    // Handles exceptions

    }

    mStore= newHealthDataStore(this, mConnectionListener);mStore.connectService();

    }

    @OverridepublicvoidonDestroy() {

    mStore.disconnectService();}

    privatefinal HealthDataStore.ConnectionListener mConnectionListener= newHealthDataStore.ConnectionListener() {

    @OverridepublicvoidonConnected() {// The connection is successful.}

    @OverridepublicvoidonConnectionFailed(HealthConnectionErrorResult error) {

    // The connection fails.error.resolve(mInstance);

    }

    @OverridepublicvoidonDisconnected() {

    // The connection is disconnected.}

    };}

    5.2.Acquiring user permission

    Users health data is private information of user and it needs be handled carefully. An application needs to acquire

    user permission before accessing health data. Its sequence is shown below.

    1)

    Implement the HealthResultHolder.ResultListenerinterface.

    2)

    Create a HealthPermissionManagerinstance.

    3)

    Add required permission set and call isPermissionAcquired().

    4)

    If user permission is not acquired yet, call requestPermissions().

  • 7/24/2019 ProgrammingGuide_HealthData

    31/59

    Samsung Digital Health - Health Data Programming Guide

    Copyright Samsung Electronics, Co., Ltd. All rights reserved. Page | 31

    5)

    The Data Framework makes the user to select the allowance for the requested permission. If the user consents

    the application can access data.

    Figure 11: Sequence diagram for acquiring user permission

    Its example code is shown below.

    importcom.samsung.android.sdk.healthdata.*;

    publicclassMainActivity extendsActivity {privateHealthDataStore mStore;privatePermissionKey mPermissionKey;

    privatevoidrequestUserPermission() {

    HealthPermissionManager pmsManager = newHealthPermissionManager(mStore);

    try{// Check whether the permissions that this application needs are acquired

    mPermissionKey= new PermissionKey(HealthConstants.StepCount.HEALTH_DATA_TYPE,PermissionType.READ);

    Set keySet = new HashSet();keySet.add(mPermissionKey);

    Map resultMap = pmsManager.isPermissionAcquired(keySet);if(resultMap.get(mPermissionKey) == Boolean.TRUE) {

    // User permission is already acquired.} else{

    // Request the permission for reading the count of steps if it is not acquiredpmsManager.requestPermissions(keySet).setResultListener( mPermissionListener);

    }} catch(Exception e) {

    // Error handling}

    }

  • 7/24/2019 ProgrammingGuide_HealthData

    32/59

    Samsung Digital Health - Health Data Programming Guide

    Copyright Samsung Electronics, Co., Ltd. All rights reserved. Page | 32

    privatefinal HealthResultHolder.ResultListener mPermissionListener=newHealthResultHolder.ResultListener() {

    @OverridepublicvoidonResult(PermissionResult result) {

    Map resultMap = result.getResultMap();

    if(resultMap.get(mPermissionKey) == Boolean.FALSE) {// Requested permission is not acquired.} else{

    // Requested permission is acquired, so the application can access data.}

    }};

    }

    To access health data, the application needs to get user permission. You need to call the permission request API, and

    the application needs to specify data types on its manifest file. If the required data type is missing on its manifest file

    the user permission API fails.

    Permissions to read and write are different entities. If the application needs to declare permission for multiple datatypes, use semicolon (;). The following example shows manifest to declare permissions for reading and writing.

    5.3.

    Inserting dataAn application can insert created data into the health data storage. The data request works either synchronously or

    asynchronously. See4.1.2 for additional information. Make sure not to make the synchronous request on the UI

    thread. The sequence for the asynchronous request is shown below.

    1)

    Implement the HealthResultHolder.ResultListenerinterface.

    2)

    Create a HealthDataResolver.InsertRequestinstance.

    3)

    Add a HealthDatainstances to InsertRequest.

    4)

    Create a HealthDataResolverinstance.

    5)

    Call insert()to insert data.

    6)

    The application can check the result asynchronously on the onResult()callback.

  • 7/24/2019 ProgrammingGuide_HealthData

    33/59

    Samsung Digital Health - Health Data Programming Guide

    Copyright Samsung Electronics, Co., Ltd. All rights reserved. Page | 33

    Figure 12: Sequence diagram for inserting data

    Its example code is shown below.

    importcom.samsung.android.sdk.healthdata.*;

    privatevoidinsertGlucose(longstart, longoffset, intvalue) {HealthDataResolver resolver = newHealthDataResolver(mStore, null);

    HealthData data = newHealthData();// all mandatory properties should be filled outdata.putLong(HealthConstants.BloodGlucose. START_TIME, start);data.putLong(HealthConstants.BloodGlucose. TIME_OFFSET, offset);data.putInt(HealthConstants.BloodGlucose.GLUCOSE, value);data.putInt(HealthConstants.BloodGlucose.MEASUREMENT_TYPE,

    HealthConstants.BloodGlucose.MEASUREMENT_TYPE_WHOLE_BLOOD);

    HealthDataResolver.InsertRequest request = new HealthDataResolver.InsertRequest.Builder().setDataType(HealthConstants.BloodGlucose. HEALTH_DATA_TYPE).build();

    try{// register the local device with the data if it is not registereddata.setSourceDevice(newHealthDeviceManager(mStore).getLocalDevice().getUuId());request.addHealthData(data);resolver.insert(request).setResultListener( mResultListener);

    } catch(Exception e) {// Error handling

    }}

    : Application

    : ResultListener : HealthDataResolver: InsertRequest

    1

    2

    3 : addHealthData()

    4

    5 : insert()

    6 : onResult()

  • 7/24/2019 ProgrammingGuide_HealthData

    34/59

    Samsung Digital Health - Health Data Programming Guide

    Copyright Samsung Electronics, Co., Ltd. All rights reserved. Page | 34

    privatefinal HealthResultHolder.ResultListener mResultListener= newHealthResultHolder.ResultListener() {

    @OverridepublicvoidonResult(BaseResult result) {

    // Check the result}

    };

    5.4.

    Updating data

    An application can update data on the health data storage. The data request works either synchronously or

    asynchronously. See4.1.2 for additional information. Make sure not to make the synchronous request on the UI

    thread. Only health data that is inserted by your application can be updated. The following example shows how to

    update the food amount of existing health data. Its sequence for the asynchronous request is shown below.

    1)

    Implement the HealthResultHolder.ResultListenerinterface.

    2)

    Create a HealthDataResolver.UpdateRequestinstance and set a filter.

    3)

    Create a HealthDataResolverinstance.

    4)

    Call update().

    5)

    The application can check the result asynchronously on the onResult()callback.

    : Application

    : ResultListener : UpdateRequest : HealthDataResolver

    1

    2

    3

    4 : update()

    5 : onResult()

  • 7/24/2019 ProgrammingGuide_HealthData

    35/59

    Samsung Digital Health - Health Data Programming Guide

    Copyright Samsung Electronics, Co., Ltd. All rights reserved. Page | 35

    Figure 13: Sequence diagram for updating data

    Its example code is shown below.

    importcom.samsung.android.sdk.healthdata.*;

    privatevoidupdateFood(floatorigAmount, floatupdatedAmount) {HealthDataResolver resolver = newHealthDataResolver(mStore, null);

    try{HealthData data = newHealthData();data.setSourceDevice(newHealthDeviceManager(mStore).getLocalDevice().getUuId());data.putFloat(HealthConstants.FoodIntake.AMOUNT, updatedAmount);

    Filter filter = Filter.eq(HealthConstants.FoodIntake.AMOUNT, origAmount);

    UpdateRequest request = newUpdateRequest.Builder().setDataType(HealthConstants.FoodIntake. HEALTH_DATA_TYPE).setFilter(filter).setHealthData(data).build();

    resolver.update(request).setResultListener( mResultListener);} catch(Exception e) {// Error handling

    }}

    privatefinal HealthResultHolder.ResultListener mResultListener= newHealthResultHolder.ResultListener() {

    @OverridepublicvoidonResult(BaseResult result) {// Check the result

    }};

    5.5.

    Deleting data

    An application can delete data on the health data storage. The data request works either synchronously or

    asynchronously. See4.1.2 for additional information. Make sure not to make the synchronous request on the UI

    thread. Only health data that is inserted by your application can be deleted. Its sequence for the asynchronous

    request is shown below.

    1)

    Implement the HealthResultHolder.ResultListenerinterface.

    2)

    Create a HealthDataResolver.DeleteRequestinstance.

    3)

    Set "datauuids" to be deleted.

    4)

    Create a HealthDataResolverinstance.

    5)

    Call delete().

    6)

    The application can check the result asynchronously on the onResult()callback.

  • 7/24/2019 ProgrammingGuide_HealthData

    36/59

    Samsung Digital Health - Health Data Programming Guide

    Copyright Samsung Electronics, Co., Ltd. All rights reserved. Page | 36

    Figure 14: Sequence diagram for deleting data

    Its example code is shown below.

    importcom.samsung.android.sdk.healthdata.*;

    privatevoiddeleteWeight(List datauuidList) {HealthDataResolver resolver = newHealthDataResolver(mStore, null);

    try{Filter filter = Filter.in(HealthConstants.Weight.UUID, datauuidList.toArray(newString[0]));

    DeleteRequest request = newDeleteRequest.Builder().setDataType(HealthConstants.Weight. HEALTH_DATA_TYPE).setFilter(filter).build();

    resolver.delete(request).setResultListener( mResultListener);} catch(Exception e) {// Error handling

    }}

    privatefinal HealthResultHolder.ResultListener mResultListener= newHealthResultHolder.ResultListener() {

    @OverridepublicvoidonResult(BaseResult result) {// Check the result

    }

    : Application

    : ResultListener : DeleteRequest : HealthDataResolver

    1

    2

    3 : deleteHealthData()

    4

    5 : delete()

    6 : onResult()

  • 7/24/2019 ProgrammingGuide_HealthData

    37/59

    Samsung Digital Health - Health Data Programming Guide

    Copyright Samsung Electronics, Co., Ltd. All rights reserved. Page | 37

    };

    5.6.

    Reading data

    An application can read data on the health data storage. The data request works either synchronously or

    asynchronously. See4.1.2 for additional information. Make sure not to make the synchronous request on the UI

    thread. The sequence for the asynchronous request is shown below.

    1)

    Implement the HealthResultHolder.ResultListenerinterface.

    2)

    Create a HealthDataResolver.ReadRequestinstance.

    3)

    Create a HealthDataResolverinstance.

    4)

    Call read().

    5)

    The application can check the result asynchronously on the onResult()callback. If the request is successful,the application gets Cursorthat contains the result.

    Figure 15: Sequence diagram for querying data

    Its example code is shown below.

    importcom.samsung.android.sdk.healthdata.*;

    : Application

    : ResultListener : ReadRequest : HealthDataResolver

    1

    2

    3

    4 : read()

    5 : onResult()

  • 7/24/2019 ProgrammingGuide_HealthData

    38/59

    Samsung Digital Health - Health Data Programming Guide

    Copyright Samsung Electronics, Co., Ltd. All rights reserved. Page | 38

    privatevoidreadStepCount(longfrom, longto) {HealthDataResolver resolver = newHealthDataResolver(mStore, null);

    Filter filter = Filter.lessThan(HealthConstants.StepCount.DIATNACE, 100);

    try{ReadRequest request = newReadRequest.Builder()

    .setDataType(HealthConstants.StepCount. HEALTH_DATA_TYPE).setFilter(filter)

    .build();

    resolver.read(request).setResultListener( mReadResultListener);} catch(Exception e) {// Error handling

    }}

    privatefinal HealthResultHolder.ResultListener mReadResultListener= newHealthResultHolder.ResultListener() {

    @OverridepublicvoidonResult(ReadResult result) {// Check and get resultif(BaseResult.STATUS_SUCCESSFUL== result.getStatus()) {

    Cursor cursor = result.getResultCursor();}

    }};

    5.7.

    Aggregating data

    An application can aggregate health data with frequently used aggregate functions like average or sum. The data

    request works either synchronously or asynchronously. See4.1.2 for additional information. Make sure not to makethe synchronous request on the UI thread. The sequence for the asynchronous request is shown below.

    1)

    Implement the HealthResultHolder.ResultListenerinterface.

    2)

    Create a HealthDataResolver.AggregateRequestinstance.

    3)

    Create a HealthDataResolverinstance.

    4)

    Call aggregate().

    5)

    The application can check the result asynchronously on the onResult()callback. If the request is successful,

    the application gets Cursorthat contains the result.

  • 7/24/2019 ProgrammingGuide_HealthData

    39/59

    Samsung Digital Health - Health Data Programming Guide

    Copyright Samsung Electronics, Co., Ltd. All rights reserved. Page | 39

    Figure 16: Sequence diagram for aggregating data

    Its example code is shown below.

    importcom.samsung.android.sdk.healthdata.*;

    privatevoidreadDailyGlucoseAverage(longfrom, longto) {HealthDataResolver resolver = newHealthDataResolver(mStore, null);

    AggregateRequest request = newAggregateRequest.Builder().setDataType(HealthConstants.BloodGlucose. HEALTH_DATA_TYPE).addFunction(AggregateFunction.AVG, HealthConstants.BloodGlucose.GLUCOSE, "average").setTimeGroup(TimeGroupUnit. DAILY, 1, HealthConstants.BloodGlucose.START_TIME,

    HealthConstants.BloodGlucose. TIME_OFFSET, "days").setSort("days", SortOrder.DESC).build();

    try{resolver.aggregate(request).setResultListener( mAggregateResultListener );

    } catch(Exception e) {// Error handling

    }}

    privatefinal HealthResultHolder.ResultListener mAggregateResultListener = newHealthResultHolder.ResultListener() {

    @OverridepublicvoidonResult(AggregateResult result) {// Check and get resultif(BaseResult.STATUS_SUCCESSFUL== result.getStatus()) {

    Cursor cursor = result.getResultCursor();}

    }};

    : Application

    : ResultListener : AggregateRequest : HealthDataResolver

    1

    2

    3

    4 : aggregate()

    5 : onResult()

  • 7/24/2019 ProgrammingGuide_HealthData

    40/59

    Samsung Digital Health - Health Data Programming Guide

    Copyright Samsung Electronics, Co., Ltd. All rights reserved. Page | 40

    5.8.Observing change

    An application can observe changes in the health data storage. If observed data type is changed, notification is

    received in its callback. The sequence is shown below.

    1)

    Implement the HealthDataObserverlistener.

    2)

    Call addObserver()to add an observer for the specific health data type.

    3)

    If the observed data type is changed, the application receives notification in theonChange()callback.

    Figure 17 Sequence diagram for observing change

    Its example code is shown below.

    importcom.samsung.android.sdk.healthdata.*;

    privatevoidaddStepCountObserver() {

    HealthDataObserver.addObserver(mStore, HealthConstants.StepCount.HEALTH_DATA_TYPE, mObserver);}

    privatefinalHealthDataObserver mObserver= newHealthDataObserver(null) {@OverridepublicvoidonChange(String dataTypeName) {

    // Changed callback}

    };

    : Application

    : HealthDataObserver

    : Platform

    1

    2 : addObserver()

    3 : onChange()

  • 7/24/2019 ProgrammingGuide_HealthData

    41/59

    Samsung Digital Health - Health Data Programming Guide

    Copyright Samsung Electronics, Co., Ltd. All rights reserved. Page | 41

    6.

    Sample Applications

    6.1.

    SimpleHealth

    Samsung Digital Health SDK provides SimpleHealthas a sample application. SimpleHealthdemonstrates how to use

    the APIs for Samsung Digital Health to retrieve and show the count of steps in today including a process to get

    permission to read HealthConstants.StepCounthealth data.

    Prerequisites to run SimpleHealthare shown below.

    -

    Prepare a device that supports Android 4.4KitKat (API level 19) or above.

    -

    Install HealthDevAppin the device.

    Figure 18 shows its screenshots.

    Figure 18: Screenshots of SimpleHealth

    Descriptions for each source file are shown below.

    File Description

    MainActivity.java

    It contains following operations.

    - Connects to the health data store.

    -

    Checks permission to read

    HealthConstants.StepCountand requestspermission if required.

  • 7/24/2019 ProgrammingGuide_HealthData

    42/59

    Samsung Digital Health - Health Data Programming Guide

    Copyright Samsung Electronics, Co., Ltd. All rights reserved. Page | 42

    -

    Provides an option menu for the permission setting.

    StepCountReporter.java

    It contains following operations.

    - Gets todays the total count of steps and show it.

    -

    Adds an observer to get notification for the count of steps

    change.

    -

    Applies changed the count of steps to the text box ofMainActivity.

    6.1.1.MainActivity

    MainActivityis derived from Android Activity. It connects to the health data store and requests permission to read

    the HealthConstants.StepCount data type from the data store. It also provides an option menu for thepermission setting to check the status for step count data.

    Connecting to Health Data Store

    The code below shows how to connect to the health data store.

    publicclassMainActivity extendsActivity {

    publicstaticfinalString APP_TAG= "SimpleHealth";privatefinalintMENU_ITEM_PERMISSION_SETTING= 1;

    privatestaticMainActivity mInstance= null;privateHealthDataStore mStore;privateSet mKeySet;privateStepCountReporter mReporter;

    @Override

    publicvoidonCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);

    mInstance= this;mKeySet= new HashSet();mKeySet.add(new PermissionKey(HealthConstants.StepCount.HEALTH_DATA_TYPE, PermissionType.READ));HealthDataService healthDataService = new HealthDataService();try{

    healthDataService.initialize( this);

    } catch(Exception e) {

    // Handles exceptions

    }

    // Create a HealthDataStore instance and set its listenermStore= newHealthDataStore(this, mConnectionListener);// Request the connection to the health data storemStore.connectService();

    }

    @OverridepublicvoidonDestroy() {

    mStore.disconnectService();super.onDestroy();

    }

  • 7/24/2019 ProgrammingGuide_HealthData

    43/59

    Samsung Digital Health - Health Data Programming Guide

    Copyright Samsung Electronics, Co., Ltd. All rights reserved. Page | 43

    Checking Permission and Requesting Permission

    The code below shows how to check and request permission forHealthConstants.StepCount.

    privatefinal HealthDataStore.ConnectionListener mConnectionListener=newHealthDataStore.ConnectionListener() {

    @OverridepublicvoidonConnected() {

    Log.d(APP_TAG, "Health data service is connected.");HealthPermissionManager pmsManager = newHealthPermissionManager(mStore);mReporter= newStepCountReporter(mStore);

    try{// Check whether the permissions that this application needs are acquiredMap resultMap = pmsManager.isPermissionAcquired(mKeySet);

    if(resultMap.containsValue(Boolean.FALSE)) {// Request the permission for reading the count of steps if it is not acquiredpmsManager.requestPermissions(keySet).setResultListener( mPermissionListener);

    } else{// Get the count of current steps and display itmReporter.start();

    }} catch(Exception e) {

    Log.e(APP_TAG, e.getClass().getName() + " - "+ e.getMessage());Log.e(APP_TAG, "Permission setting fails.");

    }}

    // ...};

    privatefinal HealthResultHolder.ResultListener mPermissionListener=newHealthResultHolder.ResultListener() {

    @Override

    publicvoidonResult(PermissionResult result) {Log.e(APP_TAG, "Permission callback is received.");Map resultMap = result.getResultMap();

    if(resultMap.containsValue(Boolean.FALSE)) {drawStepCount("");showPermissionAlarmDialog();

    } else{// Get the count of current steps and display itmReporter.start();

    }}

    };

    Permission Setting Menu

    The code below shows the permission setting menu.

    privatevoidshowPermissionAlarmDialog() {if (isFinishing()) {

    return;}

    AlertDialog.Builder alert = newAlertDialog.Builder(MainActivity.this);alert.setTitle("Notice");alert.setMessage("All permission should be acquired");

  • 7/24/2019 ProgrammingGuide_HealthData

    44/59

    Samsung Digital Health - Health Data Programming Guide

    Copyright Samsung Electronics, Co., Ltd. All rights reserved. Page | 44

    alert.setPositiveButton("OK", null);alert.show();

    }

    @OverridepublicbooleanonCreateOptionsMenu(Menu menu) {

    super.onCreateOptionsMenu(menu);

    menu.add(1, MENU_ITEM_PERMISSION_SETTING, 0, "Permission Setting");returntrue;}

    @OverridepublicbooleanonOptionsItemSelected(android.view.MenuItem item) {

    if(item.getItemId() == (MENU_ITEM_PERMISSION_SETTING )) {HealthPermissionManager pmsManager = newHealthPermissionManager(mStore);try{

    // Show user permission UI for allowing user to change optionspmsManager.requestPermissions( mKeySet).setResultListener(mPermissionListener);

    } catch(Exception e) {Log.e(APP_TAG, e.getClass().getName() + " - "+ e.getMessage());Log.e(APP_TAG, "Permission setting fails.");

    }}

    returntrue;}

    6.1.2.

    StepCountReporter

    StepCountReporterinteracts with HealthDataResolverand HealthContentObserverobjects to get today'stotal step count and updates the step count change to MainActivity. HealthDataResolver is used to read the stepcount data for today. HealthContentObserveris used to observe a change for steps.

    Reading the Count of Steps in Today

    The code below shows how to read todays step count.

    publicclassStepCountReporter {privatefinalHealthDataStore mStore;

    publicStepCountReporter(HealthDataStore store) {mStore= store;

    }

    publicvoidstart() {// Register an observer to listen changes of step count and get today step countHealthDataObserver.addObserver(mStore, HealthConstants.StepCount.HEALTH_DATA_TYPE, mObserver);readTodayStepCount();

    }

    // Read the today's step count on demandprivatevoidreadTodayStepCount() {

    HealthDataResolver resolver = newHealthDataResolver(mStore, null);

    // Set time range from start time of today to the current timelongstartTime = getStartTimeOfToday();longendTime = System.currentTimeMillis();Filter filter = Filter.and(Filter.greaterThanEquals(HealthConstants.StepCount.START_TIME,

    startTime),

  • 7/24/2019 ProgrammingGuide_HealthData

    45/59

    Samsung Digital Health - Health Data Programming Guide

    Copyright Samsung Electronics, Co., Ltd. All rights reserved. Page | 45

    Filter.lessThanEquals(HealthConstants.StepCount. START_TIME,endTime));

    HealthDataResolver.ReadRequest request = newReadRequest.Builder().setDataType(HealthConstants.StepCount. HEALTH_DATA_TYPE).setFilter(filter).build();

    try{resolver.read(request).setResultListener( mListener);} catch(Exception e) {

    Log.e(MainActivity.APP_TAG, e.getClass().getName() + " - "+ e.getMessage());Log.e(MainActivity.APP_TAG, "Getting step count fails.");

    }}

    privatelonggetStartTimeOfToday() {Calendar today = Calendar.getInstance();

    today.set(Calendar.HOUR_OF_DAY, 0);today.set(Calendar.MINUTE, 0);today.set(Calendar.SECOND, 0);today.set(Calendar.MILLISECOND, 0);

    returntoday.getTimeInMillis();}

    privatefinal HealthResultHolder.ResultListener mListener=new HealthResultHolder.ResultListener() {@OverridepublicvoidonResult(ReadResult result) {

    intcount = 0;Cursor c = null;

    try{c = result.getResultCursor();if(c != null) {

    while(c.moveToNext()) {count += c.getInt(c.getColumnIndex(HealthConstants.StepCount.COUNT));}

    }} finally{

    if(c != null) {c.close();

    }}MainActivity.getInstance().drawStepCount(String. valueof(count));

    }};

    // ...}

    Observation for Step Count Change

    The code below shows how to add an observer for step count change.

    publicclassStepCountReporter {privatefinalHealthDataStore mStore;

    publicStepCountReporter(HealthDataStore store) {mStore= store;

    }

  • 7/24/2019 ProgrammingGuide_HealthData

    46/59

    Samsung Digital Health - Health Data Programming Guide

    Copyright Samsung Electronics, Co., Ltd. All rights reserved. Page | 46

    publicvoidstart() {// Register the observer to listen changes of step count and get today step countHealthDataObserver.addObserver(mStore, HealthConstants.StepCount.HEALTH_DATA_TYPE, mObserver);readTodayStepCount();

    }//...privatefinalHealthDataObserver mObserver= newHealthDataObserver(null) {

    // Update the step count when a change event is received@OverridepublicvoidonChange(String dataTypeName) {

    Log.d(MainActivity.APP_TAG, "Observer receives a data changed event");readTodayStepCount();

    }};

    }

    6.2.FoodNote

    Samsung Digital Health SDK provides FoodNoteas a sample application. FoodNotedemonstrates how to use the APIsfor Samsung Digital Health to check the selected days calorie intake including getting permission to read and write

    health data for HealthConstants.FoodIntakeand HealthConstants.FoodInfo.

    Prerequisites to run FoodNoteare shown below.

    -

    Prepare a device that supports Android 4.4 KitKat (API level 19) or above.

    -

    Install HealthDevAppin the device.

    Figure 19 shows its screenshots.

  • 7/24/2019 ProgrammingGuide_HealthData

    47/59

    Samsung Digital Health - Health Data Programming Guide

    Copyright Samsung Electronics, Co., Ltd. All rights reserved. Page | 47

    Figure 19: Screenshots of FoodNote

    Descriptions for each source file are shown below.

    File Description

    MainActivity.java

    - Connects to the health data store.

    -

    Checks permission for HealthConstants.FoodInfoand HealthConstants.FoodIntake,and requestspermission if required.

    -

    Provides an option menu for the permission setting.

    - Shows the selected days calorie intake.

    - Adds an observer to get notification for the calories

    change.

    ChooseFoodActivity.java- Loads the food list with FoodInfoTableclass.

    -

    Choose the food from the food list.

    MealStoreActivity.java

    -

    Shows the selected days calories based on meal types.

    - Deletes food intake data after choosing the food item in

    the food list.

    FoodDataHelper.java

    - Inserts food intake data

    - Deletes food intake data

    - Reads and shows food intake data of the selected day and

    the meal type

  • 7/24/2019 ProgrammingGuide_HealthData

    48/59

    Samsung Digital Health - Health Data Programming Guide

    Copyright Samsung Electronics, Co., Ltd. All rights reserved. Page | 48

    6.2.1.MainActivity

    MainActivityis derived from Android Activity. It connects to the health data store and requests permission to read,

    write the HealthConstants.FoodIntakedata type from the data store. And it provides an option menu for thepermission setting to access food intake and food info data.

    Connecting to Health Data StoreThe code below shows how to connect to the health data store.

    publicclassMainActivity extendsActivity implementsFoodDataHelper.DailyCaloriesCallback {// ...privatestaticfinalSimpleDateFormat INDEXTIME_FORMAT= newSimpleDateFormat("yyyy/MM/dd (E)",

    Locale.US);privatestaticfinalintMENU_ITEM_PERMISSION_SETTING= 1;privatestaticMainActivity mInstance= null;

    privateHealthDataStore mStore;privateFoodDataHelper mDataHelper;privatelongmDayStartTime;

    privateTextView mDayTv;Set mPermissionkeySet= newHashSet();

    @OverridepublicvoidonCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);// ...

    HealthDataService healthDataService = newHealthDataService();try{

    healthDataService.initialize( this);} catch(Exception e) {

    // Handles exceptions

    }

    // Create a HealthDataStore instance and set its listenermStore= newHealthDataStore(this, mConnectionListener);mDataHelper= newFoodDataHelper(mStore, getBaseContext());

    // Add the read and write permissions to mPermissionKeySetmPermissionkeySet.add(new PermissionKey(FoodIntake.HEALTH_DATA_TYPE, PermissionType.READ));mPermissionkeySet.add(new PermissionKey(FoodIntake.HEALTH_DATA_TYPE, PermissionType.WRITE));mPermissionkeySet.add(newPermissionKey(FoodInfo.HEALTH_DATA_TYPE, PermissionType.READ));mPermissionkeySet.add(newPermissionKey(FoodInfo.HEALTH_DATA_TYPE, PermissionType.WRITE));

    // Request the connection to the health data storemStore.connectService();

    }

    @OverridepublicvoidonDestroy() {HealthDataObserver.removeObserver(mStore, mObserver);mStore.disconnectService();super.onDestroy();

    }

    @OverridepublicvoidonResume() {

    super.onResume();try{

    mDataHelper.readDailyIntakeCalories(MainActivity. this, mDayStartTime);} catch(Exception e) {

    Log.e(TAG, e.getClass().getName() + " - "+ e.getMessage());

  • 7/24/2019 ProgrammingGuide_HealthData

    49/59

    Samsung Digital Health - Health Data Programming Guide

    Copyright Samsung Electronics, Co., Ltd. All rights reserved. Page | 49

    }}

    publicstaticMainActivity getInstance() {returnmInstance;

    }

    publicFoodDataHelper getFoodDataHelper() {

    returnmDataHelper;}

    privatefinal HealthDataStore.ConnectionListener mConnectionListener=newHealthDataStore.ConnectionListener() {

    @OverridepublicvoidonConnected() {

    Log.d(TAG, "onConnected");HealthPermissionManager pmsManager = newHealthPermissionManager(mStore);Map permissionMap =

    pmsManager.isPermissionAcquired(mPermissionkeySet);// Check the permissions acquired or notif (permissionMap.containsValue(Boolean.FALSE)) {

    requestPermissions();}

    // Show the intake calories of the given daymDataHelper.readDailyIntakeCalories(MainActivity. this, mDayStartTime);

    }

    @OverridepublicvoidonConnectionFailed(HealthConnectionErrorResult error) {

    Log.d(TAG, "onConnectionFailed");// Set an activity to resolve the errorerror.resolve(MainActivity. this);

    }

    @OverridepublicvoidonDisconnected() {

    Log.d(TAG, "onDisconnected");

    }};

    Checking Permission and Requesting Permission

    The code below shows how to check and request permission forHealthConstants.FoodIntakeandHealthConstants.FoodInfo.

    privatevoidrequestPermissions() {HealthPermissionManager pmsManager = newHealthPermissionManager(mStore);

    try{// Show user permission UI for allowing user to change optionspmsManager.requestPermissions( mPermissionkeySet).setResultListener(mPermissionListener);

    } catch(Exception e) {Log.e(TAG, e.getClass().getName() + " - "+ e.getMessage());Log.e(TAG, "Permission setting fails.");

    }}

    privatefinal HealthResultHolder.ResultListener mPermissionListener=newHealthResultHolder.ResultListener() {

    @OverridepublicvoidonResult(PermissionResult result) {

    Map resultMap = result.getResultMap();

  • 7/24/2019 ProgrammingGuide_HealthData

    50/59

    Samsung Digital Health - Health Data Programming Guide

    Copyright Samsung Electronics, Co., Ltd. All rights reserved. Page | 50

    // Show a permission alarm and initializes the calories if permissions are not acquiredif (resultMap.values().contains(Boolean.FALSE)) {

    showPermissionAlarmDialog();} else{

    // Get the calories of Indexed time and display itmDataHelper.readDailyIntakeCalories(MainActivity. this, mDayStartTime);// Register an observer to listen changes of the caloriesHealthDataObserver.addObserver(mStore, FoodIntake.HEALTH_DATA_TYPE, mObserver);

    }}};

    privatevoidshowPermissionAlarmDialog() {if(isFinishing()) {

    return;}

    AlertDialog.Builder alert = newAlertDialog.Builder(MainActivity.this);alert.setTitle("Notice");alert.setMessage("All permissions must be acquired");alert.setPositiveButton("OK", null);alert.show();

    }

    Permission Setting Menu

    The code below shows the permission setting menu.

    publicbooleanonCreateOptionsMenu(Menu menu) {super.onCreateOptionsMenu(menu);

    menu.add(1, MENU_ITEM_PERMISSION_SETTING, 0, "Permission Setting");returntrue;

    }

    @OverridepublicbooleanonOptionsItemSelected(android.view.MenuItem item) {

    if(item.getItemId() == (MENU_ITEM_PERMISSION_SETTING)) {requestPermissions();

    }

    returntrue;}

    6.2.2.ChooseFoodActivity

    ChooseFoodinteracts with the HealthDataResolver object in FoodDataHelperto insert the selected food

    calories with the number of intake and apply the changed calories toMealStore.

    The code below shows how to choose the food from FoodInfo class and Input the number of intake.

    publicclassChooseFoodActivity extendsActivity {// ...

    @OverridepublicvoidonCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    // Get the intake day and meal type from Android Intent

  • 7/24/2019 ProgrammingGuide_HealthData

    51/59

    Samsung Digital Health - Health Data Programming Guide

    Copyright Samsung Electronics, Co., Ltd. All rights reserved. Page | 51

    mIntakeDay= getIntent().getExtras().getLong(AppConstants.BUNDLE_KEY_INTAKE_DAY);mMealType= getIntent().getExtras().getInt(AppConstants.BUNDLE_KEY_MEAL_TYPE);

    // ...

    // Load the FoodList from FoodInfoTable classList foodNameArray = newArrayList();foodNameArray.addAll(FoodInfoTable.keySet());

    Collections.sort(foodNameArray);

    // ...

    // Show a Dialog to set intake times, after tap the food from food listnameListView.setOnItemClickListener( newOnItemClickListener() {

    @OverridepublicvoidonItemClick(AdapterView parent, View view, intposition, longid) {

    mSelectedFoodType= ((TextView) view).getText().toString();AlertDialog.Builder intakeDialogBuiler = createDialogBuilder();intakeDialogBuiler.show();

    }});

    }

    privateAlertDialog.Builder createDialogBuilder() {

    AlertDialog.Builder dialogBuilder = newAlertDialog.Builder(this);// Set EditText of the dialogfinalEditText input = newEditText(this);dialogBuilder.setTitle(R.string. editTextTitle);dialogBuilder.setMessage( mSelectedFoodType+ " : "

    + FoodInfoTable.get(mSelectedFoodType).calorie+ " kcals/time");dialogBuilder.setView(input);input.setInputType(InputType. TYPE_CLASS_NUMBER| InputType.TYPE_NUMBER_FLAG_DECIMAL);

    dialogBuilder.setPositiveButton(R.string.confirm, newDialogInterface.OnClickListener() {@OverridepublicvoidonClick(DialogInterface dialog, intwhich) {

    // Take the String value (intake count) from EditTextString takeCount = input.getText().toString();// Check for null or "0" valueif(!takeCount.isEmpty() && !("0".equals(takeCount))) {

    FoodDataHelper dataHelper = MainActivity.getInstance().getFoodDataHelper();dataHelper.insertFoodInfo( mSelectedFoodType, Float.valueOf(takeCount), mMealType,

    mIntakeDay);}

    }});

    returndialogBuilder;}

    }

    6.2.3.

    MealStoreActivity

    MealStoreActivityinteracts with the HealthDataResolver object in the FoodDataHelper class to get and delete the

    calories and updates the calories.

    The code below shows how to delete selected food from food intake data.

    publicclassMealStoreActivity extendsActivity implementsFoodDataHelper.MealDetailsCallback {// ...

  • 7/24/2019 ProgrammingGuide_HealthData

    52/59

    Samsung Digital Health - Health Data Programming Guide

    Copyright Samsung Electronics, Co., Ltd. All rights reserved. Page | 52

    @OverridepublicvoidonCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    // Get the intake day and meal type from Android IntentmIntakeDay= getIntent().getExtras().getLong(AppConstants.BUNDLE_KEY_INTAKE_DAY);mMealType= getIntent().getExtras().getInt(AppConstants.BUNDLE_KEY_MEAL_TYPE);

    // ...

    mDataHelper= MainActivity.getInstance().getFoodDataHelper();// Get the cached food intake datamDataHelper.readDailyIntakeDetails(MealStoreActivity. this, mIntakeDay, mMealType);

    // ...

    findViewById(R.id.delete).setOnClickListener(newView.OnClickListener() {@OverridepublicvoidonClick(View v) {

    switch(v.getId()) {caseR.id.delete:

    intid = mCachedFoodListView.getCheckedItemPosition();if(id != ListView.INVALID_POSITION) {

    // Get the food intake UUID from mFoodNameArrayString selectedUuid = mIntakeUuidArray.get(id);// Delete the selected food by the foodintake UUIDmDataHelper.deleteFoodIntake(selectedUuid);if (!mFoodNameArray.get(id).trim().contains( "(Not Deletable)")) {

    mFoodNameArray.remove(id);}mFoodNameArray.remove(id);// Read the food intake data after deletionmDataHelper.readDailyIntakeDetails(MealStoreActivity. this,

    mIntakeDay, mMealType);// Change the UI, after deletionmCachedFoodListView.clearChoices();mNameArrayAdapter.notifyDataSetChanged();

    }break;}

    }});

    }}

    6.2.4.

    FoodDataHelper

    Inserting Food Intake Data

    The code below shows how to insert food intake data.

    publicvoidinsertFoodInfo(String foodName) {

    HealthData data = newHealthData();// Get the FoodInfoTable's key from the selected food name to use nutrition informationFoodInfoTable.FoodInfo foodInfo = FoodInfoTable.get(foodName);

    // Fill out the mandatory properties to insert datadata.putString(FoodInfo.PROVIDER_FOOD_ID, foodInfo.providerFoodId);data.putString(FoodInfo.INFO_PROVIDER, foodInfo.infoProvider);data.putString(FoodInfo.NAME, foodInfo.name);// ...

  • 7/24/2019 ProgrammingGuide_HealthData

    53/59

    Samsung Digital Health - Health Data Programming Guide

    Copyright Samsung Electronics, Co., Ltd. All rights reserved. Page | 53

    data.putFloat(FoodInfo.CALCIUM, foodInfo.calcium);data.putFloat(FoodInfo.IRON, foodInfo.iron);

    // Register the local device if it is not registereddata.setSourceDevice(newHealthDeviceManager(mStore).getLocalDevice().getUuid());

    HealthDataResolver resolver = newHealthDataResolver(mStore, null);InsertRequest r