Awesome! There's a hidden treasure in the official HarmonyOS documentation! When I was developing smart wearable apps before, I felt resources were scarce, but I didn't expect to find so many ready-to-use, high-quality cases and code in the "Best Practices" section! Today, I must share this "Lightweight Smart Wearable Development Practice" guide with everyone. After reading it, you'll definitely avoid detours and boost your development efficiency!
HarmonyOS Wearable Development Treasure Guide: In-Depth Analysis of Official Best Practice Cases
Hi everyone! Recently, I've been tinkering with HarmonyOS smart wearable app development. I thought I'd have to fumble around, but I accidentally discovered this Lightweight Smart Wearable Development Practice in the official documentation under "Best Practices" -> "Device Scenarios" -> "Wearable". It's like discovering a new continent! The document is full of hands-on code examples, covering the core pain points of wearable development. Let's pick a few highlights and walk through them with code:
1. Basics: From "Hello World" to Page Navigation
1. Project Structure & Core Files
The official docs clearly show the standard structure of a lightweight wearable project—no more black box! Key files:
- index.hml: UI layout (like HTML)
- index.css: Stylesheet
- index.js: Logic & interaction
-
config.json: App config (routing, device type
liteWearable
)
2. Dynamic Style Binding (index.js + index.hml)
No more hardcoding! The docs teach you how to change styles dynamically:
// index.js
export default {
data: {
title: 'World',
fontSize: '30px',
fontColor: '#FF0000' // Initial red
},
clickAction() { // Change style on button click
this.fontSize = '38px';
this.fontColor = '#FFFFFF'; // Change to white
}
}
<!-- index.hml -->
<text class="title" style="font-size: {{fontSize}}; color: {{fontColor}};">
Hello {{ title }}
</text>
<input type="button" value="Change Style" onclick="clickAction"></input>
Effect: Click the button, the text gets bigger and turns white! Dynamic binding makes interaction much more flexible.
2. Core Techniques: Wearable-Specific Adaptation
1. Perfect Adaptation for Round/Square Dials
Wearable screens come in all shapes. The docs provide the ultimate solution:
- Round dial baseline: Use 466px (logical pixels) as the design baseline for width and height.
-
Key layout tip: Use
display: flex; justify-content: center; align-items: center;
to center content. -
Percentage layout: Make full use of
width: 100%; height: 100%;
and set child elements' sizes in percentages to automatically adapt to different screens.
/* Round dial container - full and centered */
.container {
width: 100%;
height: 100%;
display: flex;
justify-content: center;
align-items: center;
background-color: aquamarine;
}
/* Inner elements use percentages */
.info-panel {
width: 80%;
height: 40%;
}
-
Square dial separate config: In
config.json
, usedistroFilter
to specify square screen resolutions (e.g., 408 * 480):
{
"module": {
"distroFilter": {
"screenShape": {
"policy": "include",
"value": ["rect"] // Square
},
"screenWindow": {
"policy": "include",
"value": ["408 * 480"] // Specific resolution
}
}
// ... other config
}
}
2. App Exit: Gesture Control (Swipe Right to Exit)
Wearables have few physical buttons. The docs recommend swipe right to exit for a better experience:
<!-- index.hml - Bind swipe event on the outermost container -->
<div class="container" onswipe="touchMove">
<!-- Page content -->
</div>
// index.js
import app from '@system.app'; // Import app module
export default {
touchMove(e) {
if (e.direction == 'right') { // Detect right swipe
app.terminate(); // Exit app
}
}
}
3. Security: Data Security on Wearables
Lightweight wearables also need security! The docs provide detailed examples for key management (@ohos.security.huks
) and encryption (@ohos.security.cryptoFramework
).
1. DES Encryption/Decryption Practice (Great for Resource-Limited Wearables)
The docs provide a complete DES-CBC encryption/decryption flow:
import huks from '@ohos.security.huks';
const DES_CBC_KEY_ALIAS = 'MyDesKey'; // Key alias
const IV = '12345678'; // Initialization vector
// 1. Generate DES key
function generateDesKey() {
const genProperties = [
{ tag: huks.HuksTag.HUKS_TAG_ALGORITHM, value: huks.HuksKeyAlg.HUKS_ALG_DES },
{ tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, value: huks.HuksKeySize.HUKS_DES_KEY_SIZE_64 },
{ tag: huks.HuksTag.HUKS_TAG_PURPOSE, value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT | huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT }
];
huks.generateKeyItem(DES_CBC_KEY_ALIAS, { properties: genProperties }, (err, data) => {
if (err) console.error('Key generation failed:', err);
else console.log('DES key generated successfully!');
});
}
// 2. Encrypt data (segment update - good for large data)
let cipherText = ''; // Store encryption result
function encryptData(plainText) {
const encryptProperties = [
// ... set algorithm, mode, padding, IV, etc.
];
let handle; // Encryption session handle
// Initialize encryption session
huks.initSession(DES_CBC_KEY_ALIAS, { properties: encryptProperties }, (initErr, initData) => {
if (initErr) { ... } else { handle = initData.handle; }
});
// Update data in segments (e.g., two segments)
huks.updateSession(handle, { properties: encryptProperties, inData: stringToUint8Array(plainText.substr(0, 16)) },
(updateErr, updateData) => {
if (!updateErr) cipherText = uint8ArrayToString(updateData.outData);
});
huks.updateSession(handle, { properties: encryptProperties, inData: stringToUint8Array(plainText.substr(16)) },
(updateErr, updateData) => {
if (!updateErr) cipherText += uint8ArrayToString(updateData.outData);
});
// Finish session, complete encryption
huks.finishSession(handle, { properties: encryptProperties }, (finishErr, finishData) => {
if (!finishErr) console.log('Encryption complete! CipherText:', cipherText);
});
}
// 3. Decryption (similar to encryption, just different PURPOSE)
// ... Refer to the full example in the official docs ...
Key points:
-
generateKeyItem
generates the key. -
initSession
->updateSession
(can be called multiple times) ->finishSession
to complete encryption/decryption. - Data conversion:
stringToUint8Array
/uint8ArrayToString
are essential utility functions.
2. Simple Digest Calculation (SHA256) & Secure Random Number
Quickly calculate data fingerprints or generate keys/salts:
import cryptoFramework from '@ohos.security.cryptoFramework';
// Calculate SHA256 digest
function calculateSha256(message) {
try {
let md = cryptoFramework.createMd('SHA256');
md.updateSync({ data: stringToUint8Array(message) }); // Update data
let mdResult = md.digest(); // Calculate digest
console.log('SHA256 Digest:', mdResult.data);
} catch (error) {
console.error('Digest calculation error:', error);
}
}
// Generate secure random number (for keys, IV, etc.)
function generateSecureRandom(len) {
try {
let rand = cryptoFramework.createRandom();
let randData = rand.generateRandomSync(len); // Generate len bytes of random data
console.log('Secure random number:', randData.data);
return randData.data;
} catch (error) {
console.error('Failed to generate random number:', error);
}
}
4. Device Interaction: Screen Lock Management
The docs provide simple interfaces to control the screen lock (@ohos.screenLock
):
import screenLock from '@ohos.screenLock';
// 1. Unlock screen (requires permission)
function unlockScreen() {
screenLock.unlockScreen((err) => {
if (err) console.error('Unlock failed:', err);
else console.log('Screen unlocked!');
});
}
// 2. Check if screen is locked
function checkIfLocked() {
screenLock.isScreenLocked((err, isLocked) => {
if (!err) console.log('Screen status:', isLocked ? 'Locked' : 'Unlocked');
});
}
// 3. Check if current lock screen is secure (e.g., password/PIN/biometrics)
function checkIfSecure() {
screenLock.isSecureMode((err, isSecure) => {
if (!err) console.log('Secure lock screen:', isSecure ? 'Yes' : 'No');
});
}
Treasure Entry & Summary
Let's emphasize the treasure path in the docs again:
- Go to the HarmonyOS Developer Documentation Center
- Navigate to "Guide" -> "Best Practices"
- In the left menu, find "Device Scenarios" -> "Wearable" -> "Lightweight Smart Wearable Development Practice"
Why is it a treasure?
- Ready to use: Not just theory—every point comes with runnable code snippets (HML, CSS, JS).
- Covers core scenarios: From basic layout, dynamic interaction, page routing, lifecycle, to wearable-specific round adaptation, low-power optimization, security encryption, device interaction—it's all here.
- Solves pain points: Specially optimized for lightweight wearables (like HUAWEI WATCH GT/Fit series) with limited resources.
Stop reinventing the wheel! Whether you're just starting with HarmonyOS wearable development or facing specific challenges in your project, this "Lightweight Smart Wearable Development Practice" doc is absolutely worth your time. Study it carefully and bookmark it! Go dig for treasure in the official docs—I'm sure it'll help you quickly build more stable, smoother, and safer HarmonyOS wearable apps!
If you have any interesting discoveries or pitfalls in your development, feel free to share and discuss in the comments! 🎉
Top comments (0)