Read the original article:HarmonyOS Wearables with ArkTS
Introduction
Crash detection is a key safety feature in modern wearable apps, especially for users involved in activities like cycling or running. HarmonyOS makes it possible to build responsive, low-power crash detection modules using ArkTS with minimal overhead.
Problem: What if a user wearing a smartwatch falls or crashes suddenly?
The device needs to detect this high-impact event quickly, even if the app is running in the background, and take immediate action to assist the user.
This scenario requires:
Real-time access to motion data
Threshold-based detection
Persistent background execution
Let’s see how we can implement this using ArkTS.
How It Works
- Accessing Accelerometer Data and Calculating Magnitude
We use the SensorServiceKit
to listen to accelerometer events and determine the strength of the movement:
@State message: string = 'Monitoring\nfor crash...'
@State crashDetected: boolean = false
These two state variables are used to update the UI in real time:
message
: displays the current system status (e.g., “Monitoring…”, “Crash detected!”)
crashDetected
: a flag used to conditionally render UI or trigger further actions
Now, we define the actual listener:
private startSensorListener(): void {
try {
sensor.on(sensor.SensorId.ACCELEROMETER, (data: sensor.AccelerometerResponse) => {
const magnitude = Math.sqrt(data.x * data.x + data.y * data.y + data.z * data.z)
if (magnitude > 30) {
console.info('🚨 Crash detected!')
this.message = 'It looks like\nyou’ve been in a crash.'
this.crashDetected = true
this.bringAppToFront()
}
}, { interval: 10000000 })
} catch (err) {
const e: BusinessError = err as BusinessError
console.error(`Sensor error. Code: ${e.code}, message: ${e.message}`)
}
}
The magnitude formula helps us detect crash-level acceleration using x, y, and z values.
this.message
updates the UI to reflect a detected crash.this.crashDetected
can be used to trigger an emergency button or visual feedback.
2. Ensuring Detection Works in the Background
By default, apps stop receiving sensor events when in the background. To overcome this, we use the `BackgroundTasksKit`:
private startContinuousTask(): void {
const wantAgentInfo: wantAgent.WantAgentInfo = {
wants: [{
bundleName: this.context.abilityInfo.bundleName,
abilityName: this.context.abilityInfo.name
}],
operationType: wantAgent.OperationType.START_ABILITY,
requestCode: 0,
wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG]
}
wantAgent.getWantAgent(wantAgentInfo).then((agent) => {
backgroundTaskManager.startBackgroundRunning(
this.context,
backgroundTaskManager.BackgroundMode.DATA_TRANSFER,
agent
).then(() => {
this.startSensorListener()
console.info('✅ Background task started')
}).catch((err: Error) => {
console.error(`❌ startBackgroundRunning failed: ${JSON.stringify(err)}`)
})
})
}
BackgroundMode.DATA_TRANSFER
helps retain sensor access while running in the background.The
WantAgent
keeps the task tied to the current Ability context.
Conclusion
Crash detection on HarmonyOS wearables can be achieved with minimal code by leveraging built-in kits like SensorServiceKit
and BackgroundTasksKit
. Key takeaways:
Use accelerometer magnitude to detect impact
Start the background task to ensure monitoring doesn’t stop
Always wrap sensor access in error handling
With this setup, your wearable app can respond instantly to high-impact events, even while minimized or locked.
References
https://forums.developer.huawei.com/forumPortal/en/topic/0203189325564378008?fid=0102647487706140266
Top comments (0)