Intelligent Assistant
Chat with our virtual assistant to get answers promptly.
You can manage users' exercise records by calling APIs in HMSHealthKit after integrating Health Service Kit. First, check whether your app has been granted the following scopes to operate on the exercise record data:
APIs you can call are as follows:
The start time and end time passed for writing exercise records must be later than the UNIX timestamp corresponding to January 1, 2014.
- import {HMSHealthKit, HMSHealthKitDataType, HMSHealthKitDeviceType, HMSHealthKitActivityType, DeviceInfo, DataCollector, Value, SamplePoint, SampleSet, PaceSummary, ActivityFeature, ActivitySummary, ActivityRecord, ActivityRecordInsertOptions} from '@hw-hmscore/hms-js-health'
- // Step 1: Create an ActivityRecord object with the specified workout type, start time, end time, workout statistics, time zone, and other necessary information.
- // Build device information based on the device manufacturer, device model, device UUID, and device type.
- let deviceInfo = new DeviceInfo("manufacturer", "modelName", "uuid", HMSHealthKitDeviceType.TYPE_PHONE);
- // Build a data collector based on the device information, app package name, and data type.
- let dataCollector = new DataCollector(deviceInfo, "com.health.demo", HMSHealthKitDataType.DT_ACTIVITY_FEATURE_JUMPING_ROPE);
- // Build the field value of the workout feature statistical data type based on the mappings between data types and data fields.
- const valuesActivityFeature = []
- let valueSkipNum = new Value("skip_num", "150");
- let valueStumbingNum = new Value("stumbling_rope", "0");
- let valueMaxSkipping = new Value("max_skipping_times", "1");
- let valueDoubleShake = new Value("double_shake", "0");
- let valueTripleShake = new Value("triple_shake", "0");
- valuesActivityFeature.push(valueSkipNum);
- valuesActivityFeature.push(valueStumbingNum);
- valuesActivityFeature.push(valueMaxSkipping);
- valuesActivityFeature.push(valueDoubleShake);
- valuesActivityFeature.push(valueTripleShake);
-
- // Create a samplePoint object based on the field value array, start time, end time, and metadata.
- let samplePoint = new SamplePoint(valuesActivityFeature, "1624774020000", "1624774320000", "here is customized text");
- // Create an ActivityFeature object based on the data source and samplePoint.
- let activityFeature = new ActivityFeature(dataCollector, samplePoint);
-
- // Create a piece of rope jumping speed statistics data.
- let dataCollectorJumpRope = new DataCollector(deviceInfo, "com.health.demo", HMSHealthKitDataType.DT_CONTINUOUS_SKIP_SPEED_STATISTICS);
- let valueAvg = new Value("avg", "40");
- let valueMax = new Value("max", "60");
- let valueMin = new Value("min", "20");
- const valueJumpRopeSummary = [];
- valueJumpRopeSummary.push(valueAvg);
- valueJumpRopeSummary.push(valueMax);
- valueJumpRopeSummary.push(valueMin);
- let samplePointSkipSummary = new SamplePoint(valueJumpRopeSummary, "1624774020000", "1624774320000", "here is customized text");
- const samplePoints = [];
- samplePoints.push(samplePointSkipSummary);
- let sampleSetJumpRope = new SampleSet(dataCollectorJumpRope, samplePoints);
- // Create a piece of calorie statistics data.
- let dataCollectorCaloresTotal = new DataCollector(deviceInfo, "com.health.demo", HMSHealthKitDataType.DT_CONTINUOUS_CALORIES_BURNT_TOTAL);
- let valueCaloresTotal = new Value("calories_total", "180");
- const valueCalories = [];
- valueCalories.push(valueCaloresTotal);
- let samplePointCaloresTotal = new SamplePoint(valueCalories, "1624774020000", "1624774320000", "here is customized text");
- const samplePointsCaloresTotal = [];
- samplePointsCaloresTotal.push(samplePointCaloresTotal);
- let sampleSetCalories = new SampleSet(dataCollectorCaloresTotal, samplePointsCaloresTotal);
-
- let sampleSets = [];
- sampleSets.push(sampleSetJumpRope);
- sampleSets.push(sampleSetCalories);
-
- // Build an activitySummary object based on the workout characteristics, sampling dataset, and paceSummary.
- let activitySummary = new ActivitySummary(activityFeature, sampleSets, null);
- // Create a data source for workout heart rate details.
- let dataCollectorHeartRate = new DataCollector(deviceInfo, "com.health.demo", HMSHealthKitDataType.DT_INSTANTANEOUS_EXERCISE_HEART_RATE);
- const valuesHeartRates = []
- let valueHeartRate = new Value("bpm", "120");
- valuesHeartRates.push(valueHeartRate)
-
- let samplePointHeartRate = new SamplePoint(valuesHeartRates, "1624774020000", "1624774320000", "here is customized text");
- const samplePointsHeartRate = []
- samplePointsHeartRate.push(samplePointHeartRate);
- // Sampling dataset of the details associated with the exercise record.
- let sampleSet = new SampleSet(dataCollectorHeartRate, samplePointsHeartRate);
- const sampleSetLists = []
- sampleSetLists.push(sampleSet);
-
- let activityRecord = new ActivityRecord("mysession1", "1624774020000", "1624774320000", HMSHealthKitActivityType.JUMPING_ROPE, "here", activitySummary, "+0800", "here is customized text", deviceInfo);
- // Step 2: Create an ActivityRecordInsertOptions object based on ActivityRecord and available sampling datasets or polymerized sampling point data.
- let activityRecordInsertOptions = new ActivityRecordInsertOptions(activityRecord, sampleSetLists);
-
- // Step 3: Insert ActivityRecordInsertOptions to Health Service Kit using addActivityRecord.
- HMSHealthKit.addActivityRecord(activityRecordInsertOptions).then((result) => {
- // Calling succeeded.
- console.info("addActivityRecord success: " + JSON.stringify(result))
- }).catch((error) => {
- // Calling failed.
- console.error("addActivityRecord error: " + JSON.stringify(error));
- })
Sample code for deleting exercise records from Health Service Kit:
- import {HMSHealthKit, HMSHealthKitDataType, ActivityRecordDeleteOptions} from '@hw-hmscore/hms-js-health'
- // Step 1: Create an ActivityRecordDeleteOptions object based on activityRecordIds or the start and end times.
- const subDataTypes = []
- // Build an array of the sub-data type to be deleted.
- subDataTypes.push(HMSHealthKitDataType.DT_INSTANTANEOUS_HEART_RATE)
-
- const activityRecordIds = []
- // If you do not set acitivityRecordId, comment out the next line.
- activityRecordIds.push("mysession1")
-
- // Build deleteOptions based on conditions like the time.
- let deleteOption = new ActivityRecordDeleteOptions("1624774020000", "1624774320000", subDataTypes, activityRecordIds, "true")
-
- // Step 2: Delete exercise records that match ActivityRecordDeleteOptions from Health Service Kit using deleteActivityRecord.
- HMSHealthKit.deleteActivityRecord(deleteOption).then((result) => {
- // Calling succeeded.
- console.info("deleteActivityRecord success: " + JSON.stringify(result))
- }).catch((error) => {
- // Calling failed.
- console.error("addActivityRecord error: " + JSON.stringify(error))
- })
Sample code for querying exercise records from Health Service Kit:
- import {HMSHealthKit, HMSHealthKitDataType, ActivityRecordReadOptions} from '@hw-hmscore/hms-js-health'
- // Step 1: Create an ActivityRecordReadOptions instance.
- const dataTypeNameList = []
- // Create the detailed data associated with the target exercise record.
- dataTypeNameList.push(HMSHealthKitDataType.DT_INSTANTANEOUS_EXERCISE_HEART_RATE)
- // Create parameters for reading exercise records based on the start time, end time, and detailed dataset.
- let readOption = new ActivityRecordReadOptions("1624774020000", "1624774320000", dataTypeNameList)
- // Step 2: Call getActivityRecord to obtain exercise record data.
- HMSHealthKit.getActivityRecord(readOption).then((result) => {
- // Calling succeeded.
- console.info("getActivityRecord success: " + JSON.stringify(result))
- }).catch((error) => {
- // Calling failed.
- console.error("getActivityRecord error: " + JSON.stringify(error));
- })
Create exercise records that stay alive in the background, so that your app can keep track of users' workout data in the background.
Call beginActivityRecord to start an exercise record and apply for it to run in the background for 10 minutes. Then call PA to start the foreground service.
- import {HMSHealthKit, DeviceInfo, ActivityRecord, ComponentInfo, HMSHealthKitActivityType, HMSHealthKitDeviceType} from '@hw-hmscore/hms-js-health'
-
- // Set the type of the PA to be called to 0 (Ability) or 1 (Internal Ability).
- const ABILITY_TYPE_EXTERNAL = 0;
- // Message code for starting the foreground service
- const MESSAGE_CODE_START = 1001;
- // Message code for stopping the foreground service
- const MESSAGE_CODE_STOP = 1002;
- export default {
- async beginActivityRecord() {
- // Device information
- let deviceInfo = new DeviceInfo("manufacturer", "modelName", "uuid", HMSHealthKitDeviceType.TYPE_SMART_WATCH);
-
- // Create an ActivityRecord object with the specified activity ID, start time, time zone, and other necessary information.
- let activityRecord = new ActivityRecord("mysession1", "1624774020000", "0", HMSHealthKitActivityType.YOGA, "desc", null, "+0800", "here is customized text", deviceInfo);
- // Build the screen to be displayed when the exercise record is running in the background. Note that you need to replace the app package name and screen in the sample code.
- var componentInfo = new ComponentInfo("com.huawei.ohos.healthkit.demo", "pages", "Harmony")
- // Call HMSHealthKit.beginActivityRecord to start the exercise record that stays alive in the background.
- HMSHealthKit.beginActivityRecord(activityRecord, componentInfo, (result) => {
- console.info("beginActivityRecord callback:" + new Date() + " " + JSON.stringify(result))
- // If the operation to keep the exercise record alive is canceled due to timeout or is preempted by another app, the callback needs to stop the foreground service.
- if (result.data != "0") {
- this.stopKeepBackground();
- }
- }, this.$app.$def.hmsData.eventCallbackMap).then((result) => {
- console.info("beginActivityRecord -> success :" + JSON.stringify(result))
- // If the calling is successful, call the foreground service of the Java PA.
- this.startKeepBackground();
- }).catch((error) => {
- // If the calling fails, process the failure in the callback.
- console.error("beginActivityRecord -> Error : " + JSON.stringify(error));
- });
- },
-
- // Call the PA to start the foreground service.
- startKeepBackground() {
- console.info("workout startKeepBackground begin")
- // Set the Java PA action information. Note that you need to replace your app information in the sample code.
- var action = {};
- action.bundleName = 'com.huawei.ohos.healthkit.demo';
- action.abilityName = 'com.huawei.ohos.healthkit.demo.KeepBackgroundAbility';
- action.messageCode = MESSAGE_CODE_START;
- action.abilityType = ABILITY_TYPE_EXTERNAL;
- action.syncOption = 0;
-
- FeatureAbility.callAbility(action);
- console.info("workout startOngoing done")
- },
- // Call the Java PA to stop the foreground service.
- stopKeepBackground() {
- console.info("workout stopKeepBackground begin")
- // Set the Java PA action information. Note that you need to replace your app information in the sample code.
- var action = {};
- action.bundleName = 'com.huawei.ohos.healthkit.demo';
- action.abilityName = 'com.huawei.ohos.healthkit.demo.KeepBackgroundAbility';
- action.messageCode = MESSAGE_CODE_STOP;
- action.abilityType = ABILITY_TYPE_EXTERNAL;
-
- // Call the PA ability of the corresponding action.
- FeatureAbility.callAbility(action);
- console.info("workout stopKeepBackground done")
- },
- }
In the preceding code snippet, this.$app.$def.hmsData.eventCallbackMap indicates a collection of callbacks for global events. You can define it by referring to Initializing Modules.
Call continueActivityRecord for the exercise record to stay alive in the background for 10 minutes.
Call continueActivityRecord for the exercise record to continue running in the background each time the 10-minute period is about to end during the workout. Otherwise, your app will be terminated.
- import {HMSHealthKit, DeviceInfo, ActivityRecord, ComponentInfo, HMSHealthKitActivityType, HMSHealthKitDeviceType} from '@hw-hmscore/hms-js-health'
-
- export default {
- async continueActivityRecord () {
- // Call HMSHealthKit.continueActivityRecord and pass the exercise record ID for the record to continue running in the background.
- HMSHealthKit.continueActivityRecord("mysession1").then((result) => {
- // If the calling is successful, process the result.
- console.info("continueActivityRecord -> success :" + JSON.stringify(result))
- }).catch((error) => {
- // If the calling fails, process the failure in the callback.
- console.error("continueActivityRecord -> Error : " + JSON.stringify(error));
- });
- },
- }
Call endActivityRecord to stop the exercise record and the foreground service.
- import {HMSHealthKit, DeviceInfo, ActivityRecord, ComponentInfo, HMSHealthKitActivityType, HMSHealthKitDeviceType} from '@hw-hmscore/hms-js-health'
-
- // Message code for stopping the foreground service
- const MESSAGE_CODE_STOP = 1002;
-
- export default {
- async endActivityRecord () {
- // Call the HMSHealthKit.endActivityRecord method and pass the exercise record ID to stop the exercise record.
- HMSHealthKit.endActivityRecord("mysession1").then((result) => {
- console.info("endActivityRecord -> success :" + JSON.stringify(result))
- // If the calling is successful, call the Java PA to stop the foreground service.
- this.stopKeepBackground();
- }).catch((error) => {
- // If the calling fails, process the failure in the callback.
- console.error("endActivityRecord -> Error : " + JSON.stringify(error));
- });
- },
- // Call the Java PA to stop the foreground service.
- stopKeepBackground() {
- console.info("workout stopKeepBackground begin")
- // Set the Java PA action information. Note that you need to replace your app information in the sample code.
- var action = {};
- action.bundleName = 'com.huawei.ohos.healthkit.demo';
- action.abilityName = 'com.huawei.ohos.healthkit.demo.KeepBackgroundAbility';
- action.messageCode = MESSAGE_CODE_STOP;
- action.abilityType = ABILITY_TYPE_EXTERNAL;
-
- // Call the PA ability of the corresponding action.
- FeatureAbility.callAbility(action);
- console.info("workout stopKeepBackground done")
- },
- }
- package com.huawei.ohos.healthkit.demo;
-
- // OHOS-related packages
- import ohos.aafwk.ability.Ability;
- import ohos.aafwk.content.Intent;
- import ohos.event.notification.NotificationRequest;
- import ohos.rpc.IRemoteObject;
- import ohos.hiviewdfx.HiLog;
- import ohos.hiviewdfx.HiLogLabel;
- import ohos.rpc.IRemoteBroker;
- import ohos.rpc.RemoteObject;
- import ohos.rpc.MessageParcel;
- import ohos.rpc.MessageOption;
-
- public class KeepBackgroundAbility extends Ability {
- // Define the log label.
- private static final HiLogLabel LABEL_LOG = new HiLogLabel(3, 0xD001100, "KeepBackgroundAbility");
- // Define notificationId for binding the foreground service to the notification.
- public static final int NOTIFICATION_ID = 1005;
- // Define the RemoteObject object for FA to send messages to PA.
- private MyRemote remote = new MyRemote();
-
- // When requesting the PA service, FA calls Ability.connectAbility to connect to PA. After the connection is successful, a remote object is returned in onConnect.
- @Override
- protected IRemoteObject onConnect(Intent intent) {
- super.onConnect(intent);
- return remote.asObject();
- }
-
- class MyRemote extends RemoteObject implements IRemoteBroker {
- // Message code for starting the foreground service
- private static final int START = 1001;
- // Message code for stopping the foreground service
- private static final int STOP = 1002;
-
- MyRemote() {
- super("MyService_MyRemote");
- }
-
- @Override
- public boolean onRemoteRequest(int code, MessageParcel data, MessageParcel reply, MessageOption option) {
- switch (code) {
- case START: {
- // Create a notification of the foreground service.
- sendNotification();
- HiLog.info(LABEL_LOG, "onRemoteRequest START");
- break;
- }
- case STOP: {
- // Cancel the notification of the foreground service.
- cancelNotification();
- HiLog.info(LABEL_LOG, "onRemoteRequest EXIT");
- break;
- }
- default: {
- return false;
- }
- }
- return true;
- }
-
- @Override
- public IRemoteObject asObject() {
- return this;
- }
- }
-
- @Override
- public void onStop() {
- super.onStop();
- cancelNotification();
- }
-
- @Override
- public void onCommand(Intent intent, boolean restart, int startId) {
- super.onCommand(intent, restart, startId);
- }
-
- @Override
- public void onDisconnect(Intent intent) {
- super.onDisconnect(intent);
- }
-
- // Create a notification and call keepBackgroundRunning() to bind the foreground service to the notification.
- private void sendNotification() {
- // Create a notification. The NOTIFICATION_ID constant is passed as notificationId.
- NotificationRequest request = new NotificationRequest(NOTIFICATION_ID);
- NotificationRequest.NotificationNormalContent content = new NotificationRequest.NotificationNormalContent();
- content.setTitle("Demo").setText("doing workout");
- NotificationRequest.NotificationContent notificationContent = new NotificationRequest.NotificationContent(content);
- request.setContent(notificationContent);
-
- // Bind the foreground service to the notification. The NOTIFICATION_ID constant is passed as notificationId.
- keepBackgroundRunning(NOTIFICATION_ID, request);
- }
-
- // Cancel the notification.
- private void cancelNotification() {
- cancelBackgroundRunning();
- }
- }
- {
- "backgroundModes": [
- "dataTransfer"
- ],
- "name": "com.huawei.ohos.healthkit.demo.KeepBackgroundAbility",
- "type": "service",
- "visible": true
- }