๐ง Introduction
Have you ever been blinded by your screen in a dark room, or struggled to see anything under sunlight? Manually adjusting screen brightness can be annoying and inconsistent. That's where SmartLux comes in โ a HarmonyOS wearable app that automatically adapts screen behavior to ambient light using ArkTS and sensor services.
In this article, we'll build a HarmonyOS app that reads real-time lux levels from the ambient light sensor and dynamically adjusts the UI theme and optionally screen brightness.
By the end, you'll have:
- Hands-on experience with SensorServiceKit
- A functional HarmonyOS UI that reacts to environmental light
- (Bonus) Background task setup for persistent monitoring
Letโs glow ๐ก
โ๏ธ What We'll Use
๐ฆ Project Setup
- Create a HarmonyOS Stage project with
ArkTS - Set
deviceTypetowearableorphone - Open
module.json5and add the following permissions:
"requestPermissions": [
{ "name": "ohos.permission.KEEP_BACKGROUND_RUNNING" },
{ "name": "ohos.permission.RUNNING_LOCK" }
]
๐ก Setting Up Ambient Light Sensor
We'll use sensor.on to continuously monitor the ambient light levels.
sensor.on(sensor.SensorId.AMBIENT_LIGHT, (data: sensor.LightResponse) => {
const lux = data.intensity
console.info('๐ก Lux value: ' + lux)
}, { interval: 100000000 })
๐จ Dynamic UI Theming Based on Lux
private getThemeColor(): Color {
if (this.lux < 50) return Color.Black
else if (this.lux < 500) return Color.Gray
else return Color.White
}
private getTextMessage(): string {
if (this.lux < 50) return '๐ Dim environment...'
else if (this.lux < 500) return '๐ค๏ธ Light level is moderate.'
else return 'โ๏ธ Bright as daylight!'
}
๐ Brightness Calculation (Optional)
let brightness = Math.round((lux / 1000) * 100)
brightness = Math.max(10, Math.min(100, brightness))
โ ๏ธ Limitation
@system.brightness.setValue() only works for system apps starting from **API 7**. In third-party apps, use it only for internal logic or visual feedback.
const info: 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]
}
const agent = await wantAgent.getWantAgent(info)
await backgroundTaskManager.startBackgroundRunning(this.context,
backgroundTaskManager.BackgroundMode.DATA_TRANSFER, agent)
๐ฌ Demo
๐ Conclusion
SmartLux shows how easy it is to create responsive, environment-aware apps with HarmonyOS and ArkTS. With just a few APIs and sensors, you can make your UI adaptive, energy-efficient, and user-friendly.



Top comments (0)