目录

HealthRecordController

Class Info

public class HealthRecordController

Defines the health record API. You can use this API to insert, delete, update, and read health record data.

You can obtain the HealthRecordController via the HuaweiHiHealth class.

Sample code for obtaining a HealthRecordController object:
Java
// Obtain a healthRecordController object.
// Note that this refers to an Activity object.
HealthRecordController healthRecordController = HuaweiHiHealth.getHealthRecordController(this);
Kotlin
// Obtain a healthRecordController object.
// Note that this refers to an Activity object.
val healthRecordController = HuaweiHiHealth.getHealthRecordController(this)

Public Method Summary

Qualifier and Type

Method Name and Description

Task<String>

addHealthRecord(HealthRecordInsertOptions insertOption)

Inserts health records to Health Service Kit.

Task<Void>

deleteHealthRecord(HealthRecordDeleteOptions deleteOptions)

Deletes health records based on the request parameters.

Task<HealthRecordReply>

getHealthRecord(HealthRecordReadOptions readOption)

Reads health record data. You can read data by time, data type, data collector, and more by specifying the related parameters in readOptions.

Task<Void>

updateHealthRecord(HealthRecordUpdateOptions updateOption)

Updates existing health records. If the health record to be updated does not exist, an error message is displayed.

Public Methods

[h2]addHealthRecord(HealthRecordInsertOptions insertOption)

Method

public Task<String> addHealthRecord(HealthRecordInsertOptions insertOption)

Inserts health records to Health Service Kit.

Parameters

Name

Description

insertOption

Health record parameters to be inserted to Health Service Kit.

Returns

Type

Description

Task<String>

Flag of the added health record data.

Save the flag for calling updateHealthRecord.

The sample code is as follows:
Java
// Note that this refers to an Activity object.
HealthRecordController healthRecordController = HuaweiHiHealth.getHealthRecordController(this);
// Set the start time and end time of the request body.
Calendar cal = Calendar.getInstance();
Date now = new Date();
cal.setTime(now);
long endTime = cal.getTimeInMillis();
cal.add(Calendar.HOUR_OF_DAY, -1);
long startTime = cal.getTimeInMillis();

// 1. Create a collector that carries heart rate details and a sampleSetList that stores heart rate details.
DataCollector dataCollector =
    new com.huawei.hms.hihealth.data.DataCollector.Builder().setDataType(DataType.DT_INSTANTANEOUS_HEART_RATE)
        .setDataGenerateType(DataCollector.DATA_TYPE_RAW)
        .setPackageName(getApplicationContext())
        .setDataStreamName("such as step count")
        .build();
SampleSet sampleSet = SampleSet.create(dataCollector);
// The preset time span is 5 minutes, and the sampling point of the heart rate details is 88.
SamplePoint samplePoint =
    sampleSet.createSamplePoint().setTimeInterval(startTime , startTime + 300000L, TimeUnit.MILLISECONDS);
samplePoint.getFieldValue(Field.FIELD_BPM).setDoubleValue(88);
sampleSet.addSample(samplePoint);
// sampleSetList is used to store health details.
List<SampleSet> sampleSetList = new ArrayList<>();
sampleSetList.add(sampleSet);

// 2. Create a collector that carries the heart rate statistics data type and statistical data points.
DataCollector dataCollector1 = new com.huawei.hms.hihealth.data.DataCollector.Builder()
    .setDataType(DataType.POLYMERIZE_CONTINUOUS_HEART_RATE_STATISTICS)
    .setDataGenerateType(DataCollector.DATA_TYPE_RAW)
    .setPackageName(getApplicationContext())
    .setDataStreamName("such as step count")
    .build();
// samplePointList is used to store statistical data points.
List<SamplePoint> samplePointList = new ArrayList<>();
// Build a statistical data point for heart rate.
SamplePoint samplePoint1 = new SamplePoint.Builder(dataCollector1).build();
samplePoint1.getFieldValue(Field.FIELD_AVG).setDoubleValue(90);
samplePoint1.getFieldValue(Field.FIELD_MAX).setDoubleValue(100);
samplePoint1.getFieldValue(Field.FIELD_MIN).setDoubleValue(80);
samplePoint1.getFieldValue(Field.FIELD_LAST).setDoubleValue(80);
samplePoint1.setTimeInterval(startTime + 1L, startTime + 300000L, TimeUnit.MILLISECONDS);
samplePointList.add(samplePoint1);

// 3. Create a health record collector (using the bradycardia data type as an example) and a health record structure.
DataCollector dataCollector2 = new com.huawei.hms.hihealth.data.DataCollector.Builder()
    .setDataType(HealthDataTypes.DT_HEALTH_RECORD_BRADYCARDIA)
    .setDataGenerateType(DataCollector.DATA_TYPE_RAW)
    .setPackageName(getApplicationContext())
    .setDataStreamName("such as step count")
    .build();

HealthRecord.Builder healthRecordBuilder =
    new HealthRecord.Builder(dataCollector2).setSubDataSummary(samplePointList)
        .setSubDataDetails(sampleSetList)
        .setStartTime(startTime, TimeUnit.MILLISECONDS)
        .setEndTime(endTime, TimeUnit.MILLISECONDS);
// Set a value for each field of the bradycardia data type.
healthRecordBuilder.setFieldValue(HealthFields.FIELD_THRESHOLD, 40d);
healthRecordBuilder.setFieldValue(HealthFields.FIELD_AVG_HEART_RATE, 44d);
healthRecordBuilder.setFieldValue(HealthFields.FIELD_MAX_HEART_RATE, 48d);
healthRecordBuilder.setFieldValue(HealthFields.FIELD_MIN_HEART_RATE, 40d);
HealthRecord healthRecord = healthRecordBuilder.build();

HealthRecordInsertOptions insertOptions =
    new HealthRecordInsertOptions.Builder().setHealthRecord(healthRecord).build();

healthRecordController.addHealthRecord(insertOptions).addOnSuccessListener(new OnSuccessListener<String>() {
    @Override
    public void onSuccess(String healthRecordId) {
        // Save the returned healthRecordId, which is used for updating health records.
        healthRecordIdFromInsertResult = healthRecordId;
        logger("The health record is added successfully,please save the healthRecordId! " + healthRecordId);
    }
}).addOnFailureListener(new OnFailureListener() {
    @Override
    public void onFailure(Exception e) {
        logger(e.toString());
    }
});
Kotlin
// Note that this refers to an Activity object.
val healthRecordController = HuaweiHiHealth.getHealthRecordController(this)
// Set the start time and end time of the request body.
val cal = Calendar.getInstance()
val now = Date()
cal.time = now
val endTime = cal.timeInMillis
cal.add(Calendar.HOUR_OF_DAY, -1)
val startTime = cal.timeInMillis

// 1. Create a collector that carries heart rate details and a sampleSetList that stores heart rate details.
val dataCollector =
    DataCollector.Builder().setDataType(DataType.DT_INSTANTANEOUS_HEART_RATE)
        .setDataGenerateType(DataCollector.DATA_TYPE_RAW)
        .setPackageName(applicationContext)
        .setDataStreamName("such as step count")
        .build()
val sampleSet = SampleSet.create(dataCollector)
// The preset time span is 5 minutes, and the sampling point of the heart rate details is 88.
val samplePoint =
    sampleSet.createSamplePoint().setTimeInterval(startTime , startTime + 300000L, TimeUnit.MILLISECONDS)
samplePoint.getFieldValue(Field.FIELD_BPM).setDoubleValue(88.0)
sampleSet.addSample(samplePoint)
// sampleSetList is used to store health details.
val sampleSetList = ArrayList<SampleSet>()
sampleSetList.add(sampleSet)

// 2. Create a collector that carries the heart rate statistics data type and statistical data points.
val dataCollector1 = DataCollector.Builder()
    .setDataType(DataType.POLYMERIZE_CONTINUOUS_HEART_RATE_STATISTICS)
    .setDataGenerateType(DataCollector.DATA_TYPE_RAW)
    .setPackageName(applicationContext)
    .setDataStreamName("such as step count")
    .build()
// samplePointList is used to store statistical data points.
val samplePointList = ArrayList<SamplePoint>()
// Build a statistical data point for heart rate.
val samplePoint1 = SamplePoint.Builder(dataCollector1).build()
samplePoint1.getFieldValue(Field.FIELD_AVG).setDoubleValue(90.0)
samplePoint1.getFieldValue(Field.FIELD_MAX).setDoubleValue(100.0)
samplePoint1.getFieldValue(Field.FIELD_MIN).setDoubleValue(80.0)
samplePoint1.getFieldValue(Field.FIELD_LAST).setDoubleValue(80);
samplePoint1.setTimeInterval(startTime + 1L, startTime + 300000L, TimeUnit.MILLISECONDS)
samplePointList.add(samplePoint1)

// 3. Create a health record collector (using the bradycardia data type as an example) and a health record structure.
val dataCollector2 = DataCollector.Builder()
    .setDataType(HealthDataTypes.DT_HEALTH_RECORD_BRADYCARDIA)
    .setDataGenerateType(DataCollector.DATA_TYPE_RAW)
    .setPackageName(applicationContext)
    .setDataStreamName("such as step count")
    .build()

val healthRecordBuilder = HealthRecord.Builder(dataCollector2).setSubDataSummary(samplePointList)
    .setSubDataDetails(sampleSetList)
    .setStartTime(startTime, TimeUnit.MILLISECONDS)
    .setEndTime(endTime, TimeUnit.MILLISECONDS)
// Set a value for each field of the bradycardia data type.
healthRecordBuilder.setFieldValue(HealthFields.FIELD_THRESHOLD, 40.0)
healthRecordBuilder.setFieldValue(HealthFields.FIELD_AVG_HEART_RATE, 44.0)
healthRecordBuilder.setFieldValue(HealthFields.FIELD_MAX_HEART_RATE, 48.0)
healthRecordBuilder.setFieldValue(HealthFields.FIELD_MIN_HEART_RATE, 40.0)
val healthRecord = healthRecordBuilder.build()

val insertOptions = HealthRecordInsertOptions.Builder().setHealthRecord(healthRecord).build()

healthRecordController!!.addHealthRecord(insertOptions).addOnSuccessListener { healthRecordId ->
    // Save the returned healthRecordId, which is used for updating health records.
    healthRecordIdFromInsertResult = healthRecordId
    logger("The health record is added successfully,please save the healthRecordId:\n$healthRecordId")
}.addOnFailureListener { e -> logger(e.toString()) }

If you directly copy and use the preceding sample code, the following errors will be reported. The related solutions are provided as follows:

1. healthRecordController is not defined.

Solution: healthRecordController is an object of the HealthRecordController class. You can obtain the healthRecordController via the HuaweiHiHealth class.
Java
// Obtain a healthRecordController object.
// Note that this refers to an Activity object.
HealthRecordController healthRecordController = HuaweiHiHealth.getHealthRecordController(this);
Kotlin
// Obtain a healthRecordController object.
// Note that this refers to an Activity object.
val healthRecordController = HuaweiHiHealth.getHealthRecordController(this)

2. The helper function logger is not defined.

Solution: Define the logger function. For details, see the following sample code.
Java
private static final String TAG = "HealthRecordController";

/** 
 * Also send operation result logs to the logcat.
 * 
 * @param string Log string.
 */ 
private void logger(String string) { 
    Log.i(TAG, string); 
}
Kotlin
private val TAG = "HealthRecordController"

/**
 * Also send operation result logs to the logcat.
 *
 * @param string Log string.
 */
private fun logger(string: String) {
    Log.i(TAG, string)
}

3. The character string variable healthRecordIdFromInsertResult is not defined.

Solution: healthRecordIdFromInsertResult is used as the parameter for calling updateHealthRecord. The definition is as follows. Assign a value after the insert function is successfully called.

Java
private String healthRecordIdFromInsertResult  = "";
Kotlin
private val healthRecordIdFromInsertResult  = ""

[h2]updateHealthRecord(HealthRecordUpdateOptions updateOption)

Method

public Task<Void> updateHealthRecord(HealthRecordUpdateOptions updateOption)

Updates existing health records. If the health record to be updated does not exist, an error message is displayed.

Parameters

Name

Description

updateOption

Health record parameters to be modified in Health Service Kit.

Returns

Type

Description

Task<Void>

Task object, which is used to check whether a request is successful, fails, or is complete.

The sample code is as follows:
Java
// Note that this refers to an Activity object.
HealthRecordController healthRecordController = HuaweiHiHealth.getHealthRecordController(this);
// Set the start time and end time of the request body.
Calendar cal = Calendar.getInstance();
Date now = new Date();
cal.setTime(now);
long endTime = cal.getTimeInMillis();
cal.add(Calendar.HOUR_OF_DAY, -1);
long startTime = cal.getTimeInMillis();

// 1. Create a collector that carries heart rate details and a sampleSetList that stores heart rate details.
DataCollector dataCollector =
    new com.huawei.hms.hihealth.data.DataCollector.Builder().setDataType(DataType.DT_INSTANTANEOUS_HEART_RATE)
        .setDataGenerateType(DataCollector.DATA_TYPE_RAW)
        .setPackageName(getApplicationContext())
        .setDataStreamName("such as step count")
        .build();
SampleSet sampleSet = SampleSet.create(dataCollector);
// The preset time span is 5 minutes, and the sampling point of the heart rate details is 90.
SamplePoint samplePoint =
    sampleSet.createSamplePoint().setTimeInterval(startTime , startTime + 300000L, TimeUnit.MILLISECONDS);
samplePoint.getFieldValue(Field.FIELD_BPM).setDoubleValue(90);
sampleSet.addSample(samplePoint);
// sampleSetList is used to store health details.
List<SampleSet> sampleSetList = new ArrayList<>();
sampleSetList.add(sampleSet);

// 2. Create a collector that carries the heart rate statistics data type and statistical data points.
DataCollector dataCollector1 = new com.huawei.hms.hihealth.data.DataCollector.Builder()
    .setDataType(DataType.POLYMERIZE_CONTINUOUS_HEART_RATE_STATISTICS)
    .setDataGenerateType(DataCollector.DATA_TYPE_RAW)
    .setPackageName(getApplicationContext())
    .setDataStreamName("such as step count")
    .build();
// samplePointList is used to store statistical data points.
List<SamplePoint> samplePointList = new ArrayList<>();
// Build a statistical data point for heart rate.
SamplePoint samplePoint1 = new SamplePoint.Builder(dataCollector1).build();
samplePoint1.getFieldValue(Field.FIELD_AVG).setDoubleValue(90);
samplePoint1.getFieldValue(Field.FIELD_MAX).setDoubleValue(100);
samplePoint1.getFieldValue(Field.FIELD_MIN).setDoubleValue(80);
samplePoint1.getFieldValue(Field.FIELD_LAST).setDoubleValue(80);
samplePoint1.setTimeInterval(startTime + 1L, startTime + 300000L, TimeUnit.MILLISECONDS);
samplePointList.add(samplePoint1);

// 3. Create a health record collector (using the bradycardia data type as an example) and a health record structure.
DataCollector dataCollector2 = new com.huawei.hms.hihealth.data.DataCollector.Builder()
    .setDataType(HealthDataTypes.DT_HEALTH_RECORD_BRADYCARDIA)
    .setDataGenerateType(DataCollector.DATA_TYPE_RAW)
    .setPackageName(getApplicationContext())
    .setDataStreamName("such as step count")
    .build();

HealthRecord.Builder healthRecordBuilder =
    new HealthRecord.Builder(dataCollector2).setSubDataSummary(samplePointList)
        .setSubDataDetails(sampleSetList)
        .setStartTime(startTime, TimeUnit.MILLISECONDS)
        .setEndTime(endTime, TimeUnit.MILLISECONDS);
// Set a value for each field of the bradycardia data type.
healthRecordBuilder.setFieldValue(HealthFields.FIELD_THRESHOLD, 42d);
healthRecordBuilder.setFieldValue(HealthFields.FIELD_AVG_HEART_RATE, 45d);
healthRecordBuilder.setFieldValue(HealthFields.FIELD_MAX_HEART_RATE, 48d);
healthRecordBuilder.setFieldValue(HealthFields.FIELD_MIN_HEART_RATE, 42d);
HealthRecord healthRecord = healthRecordBuilder.build();

// 4. Build the updateOptions to be updated and let them carry the healthRecordId returned after the insertion is successful.
HealthRecordUpdateOptions updateOptions = new HealthRecordUpdateOptions.Builder().setHealthRecord(healthRecord)
    .setHealthRecordId(healthRecordIdFromInsertResult)
    .build();

healthRecordController.updateHealthRecord(updateOptions).addOnSuccessListener(new OnSuccessListener<Void>() {
    @Override
    public void onSuccess(Void aVoid) {
        logger("Health record updated successfully.");
    }
}).addOnFailureListener(new OnFailureListener() {
    @Override
    public void onFailure(Exception e) {
        logger(e.toString());
    }
});
Kotlin
// Note that this refers to an Activity object.
val healthRecordController = HuaweiHiHealth.getHealthRecordController(this)
// Set the start time and end time of the request body.
val cal = Calendar.getInstance()
val now = Date()
cal.time = now
val endTime = cal.timeInMillis
cal.add(Calendar.HOUR_OF_DAY, -1)
val startTime = cal.timeInMillis

// 1. Create a collector that carries heart rate details and a sampleSetList that stores heart rate details.
val dataCollector =
    DataCollector.Builder().setDataType(DataType.DT_INSTANTANEOUS_HEART_RATE)
        .setDataGenerateType(DataCollector.DATA_TYPE_RAW)
        .setPackageName(applicationContext)
        .setDataStreamName("such as step count")
        .build()
val sampleSet = SampleSet.create(dataCollector)
// The preset time span is 5 minutes, and the sampling point of the heart rate details is 90.
val samplePoint =
    sampleSet.createSamplePoint().setTimeInterval(startTime , startTime + 300000L, TimeUnit.MILLISECONDS)
samplePoint.getFieldValue(Field.FIELD_BPM).setDoubleValue(90.0)
sampleSet.addSample(samplePoint)
// sampleSetList is used to store health details.
val sampleSetList = ArrayList<SampleSet>()
sampleSetList.add(sampleSet)

// 2. Create a collector that carries the heart rate statistics data type and statistical data points.
val dataCollector1 = DataCollector.Builder()
    .setDataType(DataType.POLYMERIZE_CONTINUOUS_HEART_RATE_STATISTICS)
    .setDataGenerateType(DataCollector.DATA_TYPE_RAW)
    .setPackageName(applicationContext)
    .setDataStreamName("such as step count")
    .build()
// samplePointList is used to store statistical data points.
val samplePointList = ArrayList<SamplePoint>()
// samplePointList is used to store statistical data points.
val samplePoint1 = SamplePoint.Builder(dataCollector1).build()
samplePoint1.getFieldValue(Field.FIELD_AVG).setDoubleValue(90.0)
samplePoint1.getFieldValue(Field.FIELD_MAX).setDoubleValue(100.0)
samplePoint1.getFieldValue(Field.FIELD_MIN).setDoubleValue(80.0)
samplePoint1.getFieldValue(Field.FIELD_LAST).setDoubleValue(80);
samplePoint1.setTimeInterval(startTime + 1L, startTime + 300000L, TimeUnit.MILLISECONDS)
samplePointList.add(samplePoint1)

// 3. Create a health record collector (using the bradycardia data type as an example) and a health record structure.
val dataCollector2 = DataCollector.Builder()
    .setDataType(HealthDataTypes.DT_HEALTH_RECORD_BRADYCARDIA)
    .setDataGenerateType(DataCollector.DATA_TYPE_RAW)
    .setPackageName(applicationContext)
    .setDataStreamName("such as step count")
    .build()

val healthRecordBuilder = HealthRecord.Builder(dataCollector2).setSubDataSummary(samplePointList)
    .setSubDataDetails(sampleSetList)
    .setStartTime(startTime, TimeUnit.MILLISECONDS)
    .setEndTime(endTime, TimeUnit.MILLISECONDS)
// Set a value for each field of the bradycardia data type.
healthRecordBuilder.setFieldValue(HealthFields.FIELD_THRESHOLD, 42.0)
healthRecordBuilder.setFieldValue(HealthFields.FIELD_AVG_HEART_RATE, 45.0)
healthRecordBuilder.setFieldValue(HealthFields.FIELD_MAX_HEART_RATE, 48.0)
healthRecordBuilder.setFieldValue(HealthFields.FIELD_MIN_HEART_RATE, 42.0)
val healthRecord = healthRecordBuilder.build()

// 4. Build the updateOptions to be updated and let them carry the healthRecordId returned after the insertion is successful.
val updateOptions = HealthRecordUpdateOptions.Builder().setHealthRecord(healthRecord)
    .setHealthRecordId(healthRecordIdFromInsertResult)
    .build()

healthRecordController!!.updateHealthRecord(updateOptions)
    .addOnSuccessListener { logger("Health record updated successfully.") }
    .addOnFailureListener { e -> logger(e.toString()) }

If you directly copy and use the preceding sample code, the following errors will be reported. The related solutions are provided as follows:

  1. healthRecordIdFromInsertResult is not defined.

    Solution: Use the value of healthRecordIdFromInsertResult in the addHealthRecord callback to define the string variable.

  2. healthRecordController is not defined.
    Solution: healthRecordController is an object of the HealthRecordController class. You can obtain the healthRecordController via the HuaweiHiHealth class.
    Java
    // Obtain a healthRecordController object.
    // Note that this refers to an Activity object.
    HealthRecordController healthRecordController = HuaweiHiHealth.getHealthRecordController(this);
    Kotlin
    // Obtain a healthRecordController object.
    // Note that this refers to an Activity object.
    val healthRecordController = HuaweiHiHealth.getHealthRecordController(this)
  1. The helper function logger is not defined.
    Solution: Define the logger function. For details, see the following sample code.
    Java
    private static final String TAG = "HealthRecordController";
    
    /** 
     * Also send operation result logs to the logcat.
     * 
     * @param string Log string.
     */ 
    private void logger(String string) { 
        Log.i(TAG, string); 
    }
    Kotlin
    private val TAG = "HealthRecordController"
    
    /**
     * Also send operation result logs to the logcat.
     *
     * @param string Log string.
     */
    private fun logger(string: String) {
        Log.i(TAG, string)
    }

[h2]getHealthRecord(HealthRecordReadOptions readOption)

Method

public Task<HealthRecordReply> getHealthRecord(HealthRecordReadOptions readOption)

Reads health record data. You can read data by time, data type, data collector, and more by specifying the related parameters in readOption.

Parameters

Name

Description

readOption

Request parameter for reading health records from Health Service Kit.

Returns

Type

Description

Task<HealthRecordReply>

Health record query response.

The sample code is as follows:
Java
// Note that this refers to an Activity object.
HealthRecordController healthRecordController = HuaweiHiHealth.getHealthRecordController(this);
// Set the start time and end time of the request body.
Calendar cal = Calendar.getInstance();
Date now = new Date();
cal.setTime(now);
long endTime = cal.getTimeInMillis();
cal.add(Calendar.DAY_OF_YEAR, -1);
long startTime = cal.getTimeInMillis();

// Build the HealthRecordReadOptions parameter for reading health records.
// The following takes reading bradycardia data (DT_HEALTH_RECORD_BRADYCARDIA) and the associated heart rate data (DT_INSTANTANEOUS_HEART_RATE) within a specific time range as an example.
// You can add other types of detailed workout data you want to read.
List<DataType> subDataTypeList = new ArrayList<>();
subDataTypeList.add(DataType.DT_INSTANTANEOUS_HEART_RATE);
HealthRecordReadOptions healthRecordReadOptions =
    new HealthRecordReadOptions.Builder().setTimeInterval(startTime, endTime, TimeUnit.MILLISECONDS)
        .readHealthRecordsFromAllApps()
        .readByDataType(HealthDataTypes.DT_HEALTH_RECORD_BRADYCARDIA)
        .setSubDataTypeList(subDataTypeList)
        .build();

// Pass the HealthRecordReadOptions parameter to query the health record.
Task<HealthRecordReply> task = healthRecordController.getHealthRecord(healthRecordReadOptions);
task.addOnSuccessListener(new OnSuccessListener<HealthRecordReply>() {
    @Override
    public void onSuccess(HealthRecordReply readResponse) {
        logger("Get HealthRecord was successful!");
        // Print the health records obtained by calling the API.
        List<HealthRecord> recordList = readResponse.getHealthRecords();
        for (HealthRecord record : recordList) {
            if (record == null) {
                continue;
            }
            dumpHealthRecord(record);
            logger("Print detailed data points associated with health records");
            for (SampleSet dataSet : record.getSubDataDetails()) {
                dumpDataSet(dataSet);
            }
        }
    }
});
task.addOnFailureListener(new OnFailureListener() {
    @Override
    public void onFailure(Exception e) {
        logger(e.toString());
    }
});
Kotlin
// Note that this refers to an Activity object.
val healthRecordController = HuaweiHiHealth.getHealthRecordController(this)
// Set the start time and end time of the request body.
val cal = Calendar.getInstance()
val now = Date()
cal.time = now
val endTime = cal.timeInMillis
cal.add(Calendar.DAY_OF_YEAR, -1)
val startTime = cal.timeInMillis

// Build the HealthRecordReadOptions parameter for reading health records.
// The following takes reading bradycardia data (DT_HEALTH_RECORD_BRADYCARDIA) and the associated heart rate data (DT_INSTANTANEOUS_HEART_RATE) within a specific time range as an example.
// You can add other types of detailed workout data you want to read.
val healthRecordReadOptions =
    HealthRecordReadOptions.Builder().setTimeInterval(startTime, endTime, TimeUnit.MILLISECONDS)
        .readHealthRecordsFromAllApps()
        .readByDataType(HealthDataTypes.DT_HEALTH_RECORD_BRADYCARDIA)
        .setSubDataTypeList(listOf(DataType.DT_INSTANTANEOUS_HEART_RATE))
        .build()

// Pass the HealthRecordReadOptions parameter to query the health record.
val task = healthRecordController!!.getHealthRecord(healthRecordReadOptions)
task.addOnSuccessListener { readResponse ->
    logger("Get HealthRecord was successful!")
    // Print the health records obtained by calling the API.
    val recordList = readResponse.healthRecords
    for (record in recordList) {
        if (record == null) {
            continue
        }
        dumpHealthRecord(record)
        logger("Print detailed data points associated with health records")
        for (dataSet in record.subDataDetails) {
            dumpDataSet(dataSet)
        }
    }
}
task.addOnFailureListener { e -> logger(e.toString()) }

If you directly copy and use the preceding sample code, the following errors will be reported. The related solutions are provided as follows:

  1. healthRecordController is not defined.
    Solution: healthRecordController is an object of the HealthRecordController class. You can obtain the healthRecordController via the HuaweiHiHealth class.
    Java
    // Obtain a healthRecordController object.
    // Note that this refers to an Activity object.
    HealthRecordController healthRecordController = HuaweiHiHealth.getHealthRecordController(this);
    Kotlin
    // Obtain a healthRecordController object.
    // Note that this refers to an Activity object.
    val healthRecordController = HuaweiHiHealth.getHealthRecordController(this)
  2. The helper function logger is not defined.
    Solution: Define the logger function. For details, see the following sample code.
    Java
    private static final String TAG = "HealthRecordController";
    
    /** 
     * Also send operation result logs to the logcat.
     * 
     * @param string Log string.
     */ 
    private void logger(String string) { 
        Log.i(TAG, string); 
    }
    Kotlin
    private val TAG = "HealthRecordController"
    
    /**
     * Also send operation result logs to the logcat.
     *
     * @param string Log string.
     */
    private fun logger(string: String) {
        Log.i(TAG, string)
    }
  3. The helper function dumpHealthRecord is not defined.
    Solution: Define the dumpHealthRecord function. For details, see the following sample code.
    Java
    /** 
      * Print the information in the HealthRecord object.
      * 
      * @param healthRecord Health record object.
      */ 
    private void dumpHealthRecord(HealthRecord healthRecord) { 
        logger("Print health record summary information!");
        DateFormat dateFormat = DateFormat.getDateInstance();
        DateFormat timeFormat = DateFormat.getTimeInstance();
        if (healthRecord != null) {
            logger("\tHealthRecordIdentifier: " + healthRecord.getHealthRecordId() + "\n\tpackageName: "
                + healthRecord.getDataCollector().getPackageName() + "\n\tStartTime: "
                + dateFormat.format(healthRecord.getStartTime(TimeUnit.MILLISECONDS)) + " "
                + timeFormat.format(healthRecord.getStartTime(TimeUnit.MILLISECONDS)) + "\n\tEndTime: "
                + dateFormat.format(healthRecord.getEndTime(TimeUnit.MILLISECONDS)) + " "
                + timeFormat.format(healthRecord.getEndTime(TimeUnit.MILLISECONDS)) + "\n\tHealthRecordDataType: "
                + healthRecord.getDataCollector().getDataType().getName() + "\n\tHealthRecordDataCollectorId: "
                + healthRecord.getDataCollector().getDataStreamId() + "\n\tmetaData: " + healthRecord.getMetadata()
                + "\n\tFileValueMap: " + healthRecord.getFieldValues());
    
            if (healthRecord.getSubDataSummary() != null && !healthRecord.getSubDataSummary().isEmpty()) {
                SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
    
                for (SamplePoint samplePoint : healthRecord.getSubDataSummary()) {
                    logger("Sample point type: " + samplePoint.getDataType().getName());
                    logger("Start: " + sDateFormat.format(new Date(samplePoint.getStartTime(TimeUnit.MILLISECONDS))));
                    logger("End: " + sDateFormat.format(new Date(samplePoint.getEndTime(TimeUnit.MILLISECONDS))));
                    for (Field field : samplePoint.getDataType().getFields()) {
                        logger("Field: " + field.getName() + " Value: " + samplePoint.getFieldValue(field));
                    }
                    logger(System.lineSeparator());
                }
            }
        }
    }
    Kotlin
    /** 
      * Print the information in the HealthRecord object.
      * 
      * @param healthRecord Health record object.
      */ 
    private fun dumpHealthRecord(healthRecord: HealthRecord?) {
        logger("Print health record summary information!")
        val dateFormat = DateFormat.getDateInstance()
        val timeFormat = getTimeInstance()
        if (healthRecord != null) {
            logger(
                "\tHealthRecordIdentifier: " + healthRecord.healthRecordId + "\n\tpackageName: "
                    + healthRecord.dataCollector.packageName + "\n\tStartTime: "
                    + dateFormat.format(healthRecord.getStartTime(TimeUnit.MILLISECONDS)) + " "
                    + timeFormat.format(healthRecord.getStartTime(TimeUnit.MILLISECONDS)) + "\n\tEndTime: "
                    + dateFormat.format(healthRecord.getEndTime(TimeUnit.MILLISECONDS)) + " "
                    + timeFormat.format(healthRecord.getEndTime(TimeUnit.MILLISECONDS)) + "\nHealthRecordDataType: "
                    + healthRecord.dataCollector.dataType.name + "\n\tHealthRecordDataCollectorId: "
                    + healthRecord.dataCollector.dataStreamId + "\n\tmetaData: " + healthRecord.metadata
                    + "\n\tFileValueMap: " + healthRecord.fieldValues
            )
    
            if (healthRecord.subDataSummary != null && !healthRecord.subDataSummary.isEmpty()) {
                val sDateFormat = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault())
    
                for (samplePoint in healthRecord.subDataSummary) {
                    logger("Sample point type: " + samplePoint.dataType.name)
                    logger("Start: " + sDateFormat.format(Date(samplePoint.getStartTime(TimeUnit.MILLISECONDS))))
                    logger("End: " + sDateFormat.format(Date(samplePoint.getEndTime(TimeUnit.MILLISECONDS))))
                    for (field in samplePoint.dataType.fields) {
                        logger("Field: " + field.name + " Value: " + samplePoint.getFieldValue(field))
                    }
                    logger(System.lineSeparator())
                }
            }
        }
    }
  1. The helper function dumpDataSet is not defined.
    Solution: Define the dumpDataSet function. For details, see the following sample code.
    Java
    /** 
      * Print the SamplePoint in the SampleSet object as an output.
      * 
      * @param sampleSet Sampling dataset.
      */ 
    private void dumpDataSet(SampleSet sampleSet) { 
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
    
        for (SamplePoint samplePoint : sampleSet.getSamplePoints()) { 
            logger("Sample point type: " + samplePoint.getDataType().getName()); 
            logger("Start: " + dateFormat.format(new Date(samplePoint.getStartTime(TimeUnit.MILLISECONDS)))); 
            logger("End: " + dateFormat.format(new Date(samplePoint.getEndTime(TimeUnit.MILLISECONDS)))); 
            for (Field field : samplePoint.getDataType().getFields()) { 
                logger("Field: " + field.getName() + " Value: " + samplePoint.getFieldValue(field)); 
            } 
        } 
    }
    Kotlin
    /**
     * Print the SamplePoint in the SampleSet object as an output.
     *
     * @param sampleSet Sampling dataset.
     */
    private fun dumpDataSet(sampleSet: SampleSet) {
        val dateFormat = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.SIMPLIFIED_CHINESE)
    
        for (samplePoint in sampleSet.samplePoints) {
            logger("Sample point type: " + samplePoint.dataType.name)
            logger("Start: " + dateFormat.format(Date(samplePoint.getStartTime(TimeUnit.MILLISECONDS))))
            logger("End: " + dateFormat.format(Date(samplePoint.getEndTime(TimeUnit.MILLISECONDS))))
            for (field in samplePoint.dataType.fields) {
                logger("Field: " + field.name + " Value: " + samplePoint.getFieldValue(field))
            }
        }
    }

[h2]deleteHealthRecord(HealthRecordDeleteOptions deleteOption)

Method

public Task<Void> deleteHealthRecord(HealthRecordDeleteOptions deleteOption)

Deletes health records based on the request parameters.

  1. You can delete health records either by record ID or by data type and start and end times. The record ID prevails when both of them exist.
  2. You can set whether to delete activity details by deleting subDataTypeList.

Parameters

Name

Description

deleteOption

Request for querying health records to be deleted. It includes healthRecordIds, start and end times, and data type.

Returns

Type

Description

Task<Void>

Task object, which is used to check whether a request is successful, fails, or is complete.

Sample code for deleting health records:
Java
// Note that this refers to an Activity object.
HealthRecordController healthRecordController = HuaweiHiHealth.getHealthRecordController(this);
// Build the start time and end time for the request object.
// Note that the start time and end time must be later than the UNIX timestamp corresponding to January 1, 2014.
Calendar cal = Calendar.getInstance();
Date now = new Date();
cal.setTime(now);
long endTime = cal.getTimeInMillis();
cal.add(Calendar.DAY_OF_YEAR, -2);
long startTime = cal.getTimeInMillis();
// Construct dataType for the request object.
DataType dataType = HealthDataTypes.DT_HEALTH_RECORD_BRADYCARDIA;
// Construct subDataTypeList for the request object.
List<DataType> subDataTypeList = Collections.singletonList(DataType.DT_INSTANTANEOUS_HEART_RATE);
// Set healthRecordIds that will be returned after the insertion is successful.
List<String> healthRecordIds = Collections.singletonList("healthRecordId");

// Construct the request body.
HealthRecordDeleteOptions deleteRequest = new HealthRecordDeleteOptions.Builder()
    .setHealthRecordIds(healthRecordIds)
    .isDeleteSubData(true)
    .setDataType(dataType)
    .setSubDataTypeList(subDataTypeList)
    .setTimeInterval(startTime, endTime, TimeUnit.MILLISECONDS).build();
// Call deleteHealthRecord to delete the health record.
Task<Void> deleteTask = healthRecordController.deleteHealthRecord(deleteRequest);
deleteTask.addOnSuccessListener(new OnSuccessListener<Void>() {
    @Override
    public void onSuccess(Void aVoid) {
        Log.i("HealthRecords","HealthRecord deleted successfully.");
    }
}).addOnFailureListener(new OnFailureListener() {
    @Override
    public void onFailure(Exception e) {
        logger(e.toString());
    }
});
Kotlin
// Note that this refers to an Activity object.
val healthRecordController = HuaweiHiHealth.getHealthRecordController(this)
// Build the start time and end time for the request object.
// Note that the start time and end time must be later than the UNIX timestamp corresponding to January 1, 2014.
val cal = Calendar.getInstance()
val now = Date()
cal.setTime(now)
val endTime = cal.getTimeInMillis()
cal.add(Calendar.DAY_OF_YEAR, -2)
val startTime = cal.getTimeInMillis()
// Construct dataType for the request object.
val dataType = HealthDataTypes.DT_HEALTH_RECORD_BRADYCARDIA
// Set healthRecordIds that will be returned after the insertion is successful.
val subDataTypeList = Collections.singletonList(DataType.DT_INSTANTANEOUS_HEART_RATE)
// Construct healthRecordIds for the request object.
val healthRecordIds = Collections.singletonList("healthRecordId")

// Construct the request body.
val deleteRequest = HealthRecordDeleteOptions.Builder()
    .setHealthRecordIds(healthRecordIds)
    .isDeleteSubData(true)
    .setDataType(dataType)
    .setSubDataTypeList(subDataTypeList)
    .setTimeInterval(startTime, endTime, TimeUnit.MILLISECONDS)
    .build()

// Call deleteHealthRecord to delete the health record.
val deleteTask = healthRecordController!!.deleteHealthRecord(deleteRequest)
deleteTask.addOnSuccessListener { Log.i("HealthRecords", "HealthRecord deleted successfully.") }
    .addOnFailureListener { e ->
        val errorCode = e.message
        val errorMsg = HiHealthStatusCodes.getStatusCodeMessage(Integer.parseInt(errorCode!!))
        Log.i("HealthRecords", "$errorCode: $errorMsg")
    }