Intelligent Assistant
Chat with our virtual assistant to get answers promptly.
After integrating Health Service Kit, you can manage users' health records by calling APIs in the HealthRecordController class.
You can use HealthRecordController to write health records to Health Service Kit as follows:
The start time and end time passed for inserting health records must be later than the UNIX timestamp corresponding to January 1, 2014.
The following is the sample code for inserting the health record of a supported data type, the bradycardia data type.
- // Note:
- // 1. this refers to an Activity object.
- // 2. Initialize objects of the HealthRecordController class each time before API calling. Otherwise, data reading may fail due to expired Activity or Context.
- 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 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(context)
- .setDataStreamName("such as step count")
- .build();
- SampleSet sampleSet = SampleSet.create(dataCollector);
- // Set the preset time span to 5 minutes, and the heart rate value of the sampling point to 88.
- SamplePoint samplePoint =
- sampleSet.createSamplePoint().setTimeInterval(startTime , startTime + 300000L, TimeUnit.MILLISECONDS);
- samplePoint.getFieldValue(Field.FIELD_BPM).setDoubleValue(88);
- sampleSet.addSample(samplePoint);
- // Set sampleSetList for storing health details.
- List<SampleSet> sampleSetList = new ArrayList<>();
- sampleSetList.add(sampleSet);
-
- // Set samplePointList for storing statistical data points.
- List<SamplePoint> samplePointList = new ArrayList<>();
- // 2. Build a statistical data point for heart rate.
- SamplePoint samplePoint1 = new SamplePoint.Builder(DataType.POLYMERIZE_CONTINUOUS_HEART_RATE_STATISTICS).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. Build 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(context)
- .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 modification.
- 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());
- }
- });
If you directly copy and use the preceding sample code, the following errors will be reported. The related solutions are provided as follows:
- 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);
- }
Solution: healthRecordIdFromInsertResult is used as the parameter for calling updateHealthRecord. The definition is as follows. Assign a value to healthRecordIdFromInsertResult after addHealthRecord is successfully called.
- private String healthRecordIdFromInsertResult = "";
You can delete health records through HealthRecordController as follows:
Sample code for deleting health records from Health Service Kit:
- // Note:
- // 1. this refers to an Activity object.
- // 2. Initialize objects of the HealthRecordController class each time before API calling. Otherwise, data reading may fail due to expired Activity or Context.
- HealthRecordController healthRecordController = HuaweiHiHealth.getHealthRecordController(this);
-
- // Build the time range of the request object: start time and end time.
- // 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();
- // Build dataType for the request object.
- DataType dataType = HealthDataTypes.DT_HEALTH_RECORD_BRADYCARDIA;
- // Build subDataTypeList for the request object.
- List<DataType> subDataTypeList = Collections.singletonList(DataType.DT_INSTANTANEOUS_HEART_RATE);
- // Build healthRecordIds for the request object.
- List<String> healthRecordIds = Collections.singletonList("healthRecordIdFromInsertResult");
-
- // Build the request body with the deletion object.
- 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) {
- Log.i("HealthRecords","Failed to delete data" + e.getMessage());
- }
- });
You can use HealthRecordController to update health records that have been written to Health Service Kit as follows:
1. The start time and end time passed for inserting health records must be later than the UNIX timestamp corresponding to January 1, 2014.
2. If no health record matching HealthRecordId is found, an error code will be thrown.
The following is the sample code for updating the health record of a supported data type, the bradycardia data type.
- // Note:
- // 1. this refers to an Activity object.
- // 2. Initialize objects of the HealthRecordController class each time before API calling. Otherwise, data reading may fail due to expired Activity or Context.
- 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 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(context)
- .setDataStreamName("such as step count")
- .build();
- SampleSet sampleSet = SampleSet.create(dataCollector);
- // Set the preset time span to 5 minutes, and the heart rate value of the sampling point to 90.
- SamplePoint samplePoint =
- sampleSet.createSamplePoint().setTimeInterval(startTime , startTime + 300000L, TimeUnit.MILLISECONDS);
- samplePoint.getFieldValue(Field.FIELD_BPM).setDoubleValue(90);
- sampleSet.addSample(samplePoint);
- // Set sampleSetList for storing health details.
- List<SampleSet> sampleSetList = new ArrayList<>();
- sampleSetList.add(sampleSet);
-
- // Set samplePointList for storing statistical data points.
- List<SamplePoint> samplePointList = new ArrayList<>();
- // 2. Build a statistical data point for heart rate.
- SamplePoint samplePoint1 = new SamplePoint.Builder(DataType.POLYMERIZE_CONTINUOUS_HEART_RATE_STATISTICS).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. Build 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(context)
- .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 updateOptions to be updated. Remember to carry healthRecordId, which will be 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());
- }
- });
If you directly copy and use the preceding sample code, the following errors will be reported. The related solutions are provided as follows:
Solution: Define the string variable using the value of HealthRecordId that is used in the callback for writing health records to Health Service Kit.
- 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);
- }
You can use HealthRecordController to query health records that have been written to Health Service Kit as follows:
The following is the sample code for querying the health record of a supported data type, the bradycardia data type.
- // Note:
- // 1. this refers to an Activity object.
- // 2. Initialize objects of the HealthRecordController class each time before API calling. Otherwise, data reading may fail due to expired Activity or Context.
- 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.
- 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 obtained health records.
- 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());
- }
- });
If you directly copy and use the preceding sample code, the following errors will be reported. The related solutions are provided as follows:
- 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);
- }
Solution: Define the dumpHealthRecord function as follows:
- /**
- * 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());
- }
- }
- }
- }
- /**
- * Print 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));
- }
- }
- }