After integrating Health Kit, the app is able to call ten methods in DataController to perform operations on the fitness and health data. The methods include:
The 10 methods are encapsulated in the DataController object. Therefore, before any of the methods can be called, a DataController object must first be initialized. Subsequent service API calling is implemented by calling the related methods in the DataController object. The sample code for initializing a DataController object is as follows:
HiHealthOptions hiHealthOptions = HiHealthOptions.builder()
.addDataType(DataType.DT_CONTINUOUS_STEPS_DELTA, HiHealthOptions.ACCESS_READ)
.addDataType(DataType.DT_CONTINUOUS_STEPS_DELTA, HiHealthOptions.ACCESS_WRITE)
.addDataType(DataType.DT_INSTANTANEOUS_HEIGHT, HiHealthOptions.ACCESS_READ)
.addDataType(DataType.DT_INSTANTANEOUS_HEIGHT, HiHealthOptions.ACCESS_WRITE)
.build();
AuthHuaweiId signInHuaweiId = HuaweiIdAuthManager.getExtendedAuthResult(hiHealthOptions);
DataController dataController = HuaweiHiHealth.getDataController(context, signInHuaweiId);
In this development guide, data types DataType.DT_CONTINUOUS_STEPS_DELTA (number of steps taken since the last reading) and DataType.DT_INSTANTANEOUS_HEIGHT (height) are used as examples. Only the read & write permissions of these two data types are obtained for the initialized DataController object.
Insert the user's fitness and health data into the Health platform.
DataCollector dataCollector = new DataCollector.Builder().setPackageName(context)
.setDataType(DataType.DT_CONTINUOUS_STEPS_DELTA)
.setDataStreamName("STEPS_DELTA")
.setDataGenerateType(DataCollector.DATA_TYPE_RAW)
.build(); final SampleSet sampleSet = SampleSet.create(dataCollector);
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
Date startDate = dateFormat.parse("2020-03-17 09:00:00");
Date endDate = dateFormat.parse("2020-03-17 09:05:00");
int stepsDelta = 1000; SamplePoint samplePoint = sampleSet.createSamplePoint() .setTimeInterval(startDate.getTime(), endDate.getTime(), TimeUnit.MILLISECONDS); samplePoint.getFieldValue(Field.FIELD_STEPS_DELTA).setIntValue(stepsDelta);
sampleSet.addSample(samplePoint);
Task<Void> insertTask = dataController.insert(sampleSet);
insertTask.addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void result) {
logger("Success insert a SampleSet into HMS core");
showSampleSet(sampleSet);
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(Exception e) {
String errorCode = e.getMessage();
String errorMsg = HiHealthStatusCodes.getStatusCodeMessage(Integer.parseInt(errorCode));
logger(errorCode + ": " + errorMsg);
}
});
In the preceding code snippet, two helper functions are used: showSampleSet (SampleSet sampleSet) and logger(String string). The former is used to display data returned by the Health platform, and the latter is a TextView function used to save the results to the log as an output and display the results on the UI. The sample code for these two functions is as follows:
/**
* Print the SamplePoint in the SampleSet object as an output.
*
* @param sampleSet Sampling dataset.
*/
private void showSampleSet(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));
}
}
}
/**
* TextView to send the operation result logs to the logcat and to the UI
*
* @param string Log string.
*/
private void logger(String string) {
Log.i(TAG, string);
logInfoView.append(string + System.lineSeparator());
int offset = logInfoView.getLineCount() * logInfoView.getLineHeight();
if (offset > logInfoView.getHeight()) {
logInfoView.scrollTo(0, offset - logInfoView.getHeight());
}
} Only historical data that has been inserted by the app can be deleted from the Health platform. If the deletion is targeted at data not inserted by the app, the request will fail.
DataCollector dataCollector = new DataCollector.Builder().setPackageName(context)
.setDataType(DataType.DT_CONTINUOUS_STEPS_DELTA)
.setDataStreamName("STEPS_DELTA")
.setDataGenerateType(DataCollector.DATA_TYPE_RAW)
.build(); SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
Date startDate = dateFormat.parse("2020-03-17 09:00:00");
Date endDate = dateFormat.parse("2020-03-17 09:05:00"); DeleteOptions deleteOptions = new DeleteOptions.Builder().addDataCollector(dataCollector) .setTimeInterval(startDate.getTime(), endDate.getTime(), TimeUnit.MILLISECONDS) .build();
Task<Void> deleteTask = dataController.delete(deleteOptions);
deleteTask.addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void result) {
logger("Success delete sample data from HMS core");
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(Exception e) {
String errorCode = e.getMessage();
String errorMsg = HiHealthStatusCodes.getStatusCodeMessage(Integer.parseInt(errorCode));
logger(errorCode + ": " + errorMsg);
}
});
In the preceding code snippet, a helper function is used: logger(String string). This is a TextView function used to save the results to the log as an output and display the results on the UI. The sample code for the function is as follows:
/**
* TextView to send the operation result logs to the logcat and to the UI
*
* @param string Log string.
*/
private void logger(String string) {
Log.i(TAG, string);
logInfoView.append(string + System.lineSeparator());
int offset = logInfoView.getLineCount() * logInfoView.getLineHeight();
if (offset > logInfoView.getHeight()) {
logInfoView.scrollTo(0, offset - logInfoView.getHeight());
}
} DataCollector dataCollector = new DataCollector.Builder().setPackageName(context)
.setDataType(DataType.DT_CONTINUOUS_STEPS_DELTA)
.setDataStreamName("STEPS_DELTA")
.setDataGenerateType(DataCollector.DATA_TYPE_RAW)
.build(); SampleSet sampleSet = SampleSet.create(dataCollector);
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
Date startDate = dateFormat.parse("2020-03-17 09:00:00");
Date endDate = dateFormat.parse("2020-03-17 09:05:00");
int stepsDelta = 2000; SamplePoint samplePoint = sampleSet.createSamplePoint() .setTimeInterval(startDate.getTime(), endDate.getTime(), TimeUnit.MILLISECONDS); samplePoint.getFieldValue(Field.FIELD_STEPS_DELTA).setIntValue(stepsDelta);
sampleSet.addSample(samplePoint);
UpdateOptions updateRequest = new UpdateOptions.Builder() .setTimeInterval(startDate.getTime(), endDate.getTime(), TimeUnit.MILLISECONDS) .setSampleSet(sampleSet) .build();
Task<Void> updateTask = dataController.update(updateRequest);
updateTask.addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void result) {
logger("Success update sample data from HMS core");
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(Exception e) {
String errorCode = e.getMessage();
String errorMsg = HiHealthStatusCodes.getStatusCodeMessage(Integer.parseInt(errorCode));
logger(errorCode + ": " + errorMsg);
}
});
In the preceding code snippet, a helper function is used: logger(String string). This is a TextView function used to save the results to the log as an output and display the results on the UI. The sample code for the function is as follows:
/**
* TextView to send the operation result logs to the logcat and to the UI
*
* @param string Log string.
*/
private void logger(String string) {
Log.i(TAG, string);
logInfoView.append(string + System.lineSeparator());
int offset = logInfoView.getLineCount() * logInfoView.getLineHeight();
if (offset > logInfoView.getHeight()) {
logInfoView.scrollTo(0, offset - logInfoView.getHeight());
}
} To read historical data from the Health platform, for example, to read the number of steps taken within a period of time, you can specify the read conditions in ReadOptions. For example, you can specify the data collector, data type, and detailed data. If data is read, the dataset will be returned.
DataCollector dataCollector = new DataCollector.Builder().setPackageName(context)
.setDataType(DataType.DT_CONTINUOUS_STEPS_DELTA)
.setDataStreamName("STEPS_DELTA")
.setDataGenerateType(DataCollector.DATA_TYPE_RAW)
.build(); SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
Date startDate = dateFormat.parse("2020-03-17 09:00:00");
Date endDate = dateFormat.parse("2020-03-17 09:05:00"); ReadOptions readOptions = new ReadOptions.Builder().read(dataCollector) .setTimeRange(startDate.getTime(), endDate.getTime(), TimeUnit.MILLISECONDS) .build();
Task<ReadReply> readReplyTask = dataController.read(readOptions);
readReplyTask.addOnSuccessListener(new OnSuccessListener<ReadReply>() {
@Override
public void onSuccess(ReadReply readReply) {
logger("Success read a SampleSets from HMS core");
for (SampleSet sampleSet : readReply.getSampleSets()) {
showSampleSet(sampleSet);
}
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(Exception e) {
String errorCode = e.getMessage();
String errorMsg = HiHealthStatusCodes.getStatusCodeMessage(Integer.parseInt(errorCode));
logger(errorCode + ": " + errorMsg);
}
});
In the preceding code snippet, two helper functions are used: showSampleSet (SampleSet sampleSet) and logger(String string). The former is used to display data returned by the Health platform, and the latter is a TextView function used to save the results to the log as an output and display the results on the UI. The sample code for these two functions is as follows:
/**
* Print the SamplePoint in the SampleSet object as an output.
*
* @param sampleSet Sampling dataset.
*/
private void showSampleSet(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));
}
}
}
/**
* TextView to send the operation result logs to the logcat and to the UI
*
* @param string Log string.
*/
private void logger(String string) {
Log.i(TAG, string);
logInfoView.append(string + System.lineSeparator());
int offset = logInfoView.getLineCount() * logInfoView.getLineHeight();
if (offset > logInfoView.getHeight()) {
logInfoView.scrollTo(0, offset - logInfoView.getHeight());
}
} Task<SampleSet> todaySummationTask = dataController.readTodaySummation(DataType.DT_CONTINUOUS_STEPS_DELTA);
Note: In this example, the inserted data time is fixed at 2020-03-17 09:05:00. You need to change the inserted data time to the current date for data to be queried.
todaySummationTask.addOnSuccessListener(new OnSuccessListener<SampleSet>() {
@Override
public void onSuccess(SampleSet sampleSet) {
logger("Success read today summation from HMS core");
if (sampleSet != null) {
showSampleSet(sampleSet);
}
}
});
todaySummationTask.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(Exception e) {
String errorCode = e.getMessage();
String errorMsg = HiHealthStatusCodes.getStatusCodeMessage(Integer.parseInt(errorCode));
logger(errorCode + ": " + errorMsg);
}
});
In the preceding code snippet, two helper functions are used: showSampleSet (SampleSet sampleSet) and logger(String string). The former is used to display data returned by the Health platform, and the latter is a TextView function used to save the results to the log as an output and display the results on the UI. The sample code for these two functions is as follows:
/**
* Print the SamplePoint in the SampleSet object as an output.
*
* @param sampleSet Sampling dataset.
*/
private void showSampleSet(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));
}
}
}
/**
* TextView to send the operation result logs to the logcat and to the UI
*
* @param string Log string.
*/
private void logger(String string) {
Log.i(TAG, string);
logInfoView.append(string + System.lineSeparator());
int offset = logInfoView.getLineCount() * logInfoView.getLineHeight();
if (offset > logInfoView.getHeight()) {
logInfoView.scrollTo(0, offset - logInfoView.getHeight());
}
} Task<SampleSet> todaySummationTask = dataController.readTodaySummationFromDevice(DataType.DT_CONTINUOUS_STEPS_DELTA);
todaySummationTask.addOnSuccessListener(new OnSuccessListener<SampleSet>() {
@Override
public void onSuccess(SampleSet sampleSet) {
logger("Success read today device summation from HMS core");
if (sampleSet != null) {
showSampleSet(sampleSet);
}
}
});
todaySummationTask.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(Exception e) {
String errorCode = e.getMessage();
String errorMsg = HiHealthStatusCodes.getStatusCodeMessage(Integer.parseInt(errorCode));
logger(errorCode + ": " + errorMsg);
}
});
In the preceding code snippet, two helper functions are used: showSampleSet (SampleSet sampleSet) and logger(String string). The former is used to display data returned by the Health platform, and the latter is a TextView function used to save the results to the log as an output and display the results on the UI. The sample code for these two functions is as follows:
/**
* Print the SamplePoint in the SampleSet object as an output.
*
* @param sampleSet Sampling dataset.
*/
private void showSampleSet(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));
}
}
}
/**
* TextView to send the operation result logs to the logcat and to the UI
*
* @param string Log string.
*/
private void logger(String string) {
Log.i(TAG, string);
logInfoView.append(string + System.lineSeparator());
int offset = logInfoView.getLineCount() * logInfoView.getLineHeight();
if (offset > logInfoView.getHeight()) {
logInfoView.scrollTo(0, offset - logInfoView.getHeight());
}
} DataCollector dataCollector = new DataCollector.Builder().setPackageName(context)
.setDataType(DataType.DT_INSTANTANEOUS_HEIGHT)
.setDataStreamName("STEPS_DELTA")
.setDataGenerateType(DataCollector.DATA_TYPE_RAW)
.build(); PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, new Intent(this, DataRegisterReceiver.class), PendingIntent.FLAG_UPDATE_CURRENT);
ModifyDataMonitorOptions dataMonitorOptions = new ModifyDataMonitorOptions.Builder().setModifyDataType(DataType.DT_INSTANTANEOUS_HEIGHT) .setModifyDataCollector(dataCollector) .setModifyDataIntent(pendingIntent) .build();
Task<Void> registerTask = dataController.registerModifyDataMonitor(dataMonitorOptions);
registerTask.addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void result) {
logger("Register Data Update Listener Success");
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(Exception e) {
String errorCode = e.getMessage();
String errorMsg = HiHealthStatusCodes.getStatusCodeMessage(Integer.parseInt(errorCode));
logger("Register Data Update Listener Failure: " + errorCode + ": " + errorMsg);
pendingIntent = null;
}
}); DataCollector dataCollector = new DataCollector.Builder().setPackageName(context)
.setDataType(DataType.DT_INSTANTANEOUS_HEIGHT)
.setDataStreamName("STEPS_DELTA")
.setDataGenerateType(DataCollector.DATA_TYPE_RAW)
.build();
SampleSet sampleSet = SampleSet.create(dataCollector);
SamplePoint samplePoint = sampleSet.createSamplePoint()
.setTimeInterval(System.currentTimeMillis(), System.currentTimeMillis(), TimeUnit.MILLISECONDS);
samplePoint.getFieldValue(Field.FIELD_HEIGHT).setFloatValue(1.56f);
sampleSet.addSample(samplePoint);
dataController.insert(sampleSet);
In the preceding code snippet, a helper function is used: logger(String string).
This is a TextView function used to save the results to the log as an output and display the results on the UI. The sample code for the function is as follows:
/**
* TextView to send the operation result logs to the logcat and to the UI
*
* @param string Log string.
*/
private void logger(String string) {
Log.i(TAG, string);
logInfoView.append(string + System.lineSeparator());
int offset = logInfoView.getLineCount() * logInfoView.getLineHeight();
if (offset > logInfoView.getHeight()) {
logInfoView.scrollTo(0, offset - logInfoView.getHeight());
}
} PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, new Intent(this, DataRegisterReceiver.class), PendingIntent.FLAG_UPDATE_CURRENT);
Task<Void> task = dataController.unregisterModifyDataMonitor(pendingIntent);
task.addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void result) {
logger("Unregister Data Update Listener Success: ");
pendingIntent = null;
}
});
task.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(Exception e) {
String errorCode = e.getMessage();
String errorMsg = HiHealthStatusCodes.getStatusCodeMessage(Integer.parseInt(errorCode));
logger("Unregister Data Update Listener Failure: " + errorCode + ":" + errorMsg);
}
});
In the preceding code snippet, a helper function is used: logger(String string). This is a TextView function used to save the results to the log as an output and display the results on the UI. The sample code for the function is as follows:
/**
* TextView to send the operation result logs to the logcat and to the UI
*
* @param string Log string.
*/
private void logger(String string) {
Log.i(TAG, string);
logInfoView.append(string + System.lineSeparator());
int offset = logInfoView.getLineCount() * logInfoView.getLineHeight();
if (offset > logInfoView.getHeight()) {
logInfoView.scrollTo(0, offset - logInfoView.getHeight());
}
} Task<Void> syncTask = dataController.syncAll();
syncTask.addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void result) {
logger("synAll success");
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(Exception e) {
String errorCode = e.getMessage();
String errorMsg = HiHealthStatusCodes.getStatusCodeMessage(Integer.parseInt(errorCode));
logger("synAll failure" + errorCode + ":" + errorMsg);
}
});
In the preceding code snippet, a helper function is used: logger(String string). This is a TextView function used to save the results to the log as an output and display the results on the UI. The sample code for the function is as follows:
/**
* TextView to send the operation result logs to the logcat and to the UI
*
* @param string Log string.
*/
private void logger(String string) {
Log.i(TAG, string);
logInfoView.append(string + System.lineSeparator());
int offset = logInfoView.getLineCount() * logInfoView.getLineHeight();
if (offset > logInfoView.getHeight()) {
logInfoView.scrollTo(0, offset - logInfoView.getHeight());
}
} Task<Void> syncTask = dataController.clearAll();
syncTask.addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void result) {
logger("clearAll success");
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(Exception e) {
String errorCode = e.getMessage();
String errorMsg = HiHealthStatusCodes.getStatusCodeMessage(Integer.parseInt(errorCode));
logger("clearAll failure" + errorCode + ":" + errorMsg);
}
});
In the preceding code snippet, a helper function is used: logger(String string). This is a TextView function used to save the results to the log as an output and display the results on the UI. The sample code for the function is as follows:
/**
* TextView to send the operation result logs to the logcat and to the UI
*
* @param string Log string.
*/
private void logger(String string) {
Log.i(TAG, string);
logInfoView.append(string + System.lineSeparator());
int offset = logInfoView.getLineCount() * logInfoView.getLineHeight();
if (offset > logInfoView.getHeight()) {
logInfoView.scrollTo(0, offset - logInfoView.getHeight());
}
}