Requirement Description
Get heart rate with the Sensor Kit, and show on the wearable watch screen with the particle animation background.
Background Knowledge
Sensor Service Kit enables applications to obtain raw data from sensors and provides vibration control capabilities.
Implementation Steps
1) Get permission from the user
2) Get heart rate with sensor
3) Create the UI. Add a particle background (optional) and show the heart rate on the screen in real time.
Code Snippet / Configuration
1) Get permission from the user
@Entry
@Component
export struct HeartRatePage {
@State heartRate: number = 0;
aboutToAppear() {
this.requestHealthPermission(); // get permission when app open
}
}
// get permissions
async requestHealthPermission() {
const context = getContext(this);
const atManager = abilityAccessCtrl.createAtManager();
const permissions: Permissions[] = [
'ohos.permission.READ_HEALTH_DATA',
'ohos.permission.GET_NETWORK_INFO',
'ohos.permission.INTERNET'
];
try {
const result = await atManager.requestPermissionsFromUser(context, permissions);
console.info('Permissions granted: ' + JSON.stringify(result));
if (result.authResults.every(r => r === 0)) {
console.info('All permissions granted');
this.subscribeHeartRateSensor();
} else {
console.error('One or more permission rejected.');
}
} catch (err) {
console.error('Failed to get permission: ' + JSON.stringify(err));
}
}
2) get heart rate with sensor
// get heart rate sensor
subscribeHeartRateSensor() {
sensor.getSensorList((error: BusinessError, data: Array<sensor.Sensor>) => {
if (error) {
console.error('getSensorList error: ' + JSON.stringify(error));
return;
}
const heartRateSensor = data.find(s => s.sensorName.toLowerCase().includes('heart'));
if (!heartRateSensor) {
console.error('Heart rate sensor cannot be found');
return;
}
console.info('Heart rate sensor found ' + JSON.stringify(heartRateSensor));
// Continuous data retrieval
sensor.on(sensor.SensorId.HEART_RATE, (data: sensor.HeartRateResponse) => {
if (data && data.heartRate !== undefined) {
this.heartRate = data.heartRate;
console.info("HeartRate: " + data.heartRate);
}
}, { interval: 100000000 }); // 100ms (nano)
});
}
3) Create the UI. Add a particle background (optional) and show the heart rate on the screen in real time.
build() {
Column() {
Stack() {
Text()
.width(300).height(300).backgroundColor(Color.Black)
Particle({
particles: [
{
emitter: {
particle: {
type: ParticleType.POINT, // Particle type.
config: {
radius: 5 // Point radius.
},
count: 255, // Total number of particles.
},
},
color: {
range: [Color.White, Color.Red], // Initial color range.
},
},
]
}).width(200).height(200)
}.width("10%").height("10%").align(Alignment.Top)
Image($r('app.media.heartrate')).width(50).height(50).margin({ bottom: 10 })
Text("Heart Rate: " + this.heartRate + " bpm")
.fontSize(18)
.fontWeight(FontWeight.Bold)
.fontColor(Color.White)
}
.justifyContent(FlexAlign.Center)
.alignItems(HorizontalAlign.Center)
.width('100%')
.height('100%')
.backgroundColor(Color.Black)
}
Test Results
Tested on the Huawei Watch 5 device. It works as expected.
Output(it's from the previewer to show the result UI) - you need to test on a real device.
Limitations or Considerations
- To obtain data from some sensors, you need to request the required permissions.
{
"name": "ohos.permission.READ_HEALTH_DATA",
"reason": "$string:READ_HEALTH_DATA",
"usedScene": {
"abilities": [
"EntryAbility"
],
"when": "inuse"
}
}
- To use sensor functions, ensure that the device where your application runs has the required sensor components.
- Run this project on a real device.
Related Documents or Links
https://developer.huawei.com/consumer/en/doc/harmonyos-guides/sensor-guidelines

Top comments (0)