HarmonyOS(鸿蒙)是华为面向全场景智慧化时代,自主研发的一款全新的分布式操作系统。它基于微内核架构设计,采用分布式技术,能够实现跨终端无缝协同体验,为不同设备的智能化、互联与协同提供了统一的操作系统。
核心理念:| 对比维度 | HarmonyOS | Android |
|---|---|---|
| 内核架构 | 微内核(LiteOS/AliOS) | 宏内核(Linux) |
| 分布式能力 | 原生支持,系统级 | 需要第三方SDK或厂商定制 |
| 开发语言 | ArkTS、C/C++、Java | Java/Kotlin |
| 应用包格式 | .app / .hap | .apk/.aab |
| 性能特点 | 轻量、低时延、高安全 | 生态成熟,资源丰富 |
| 适用场景 | 全场景IoT、智能终端 | 以手机为主 |
HarmonyOS 采用分层架构设计,从上到下依次为:
┌─────────────────────────────────────────────┐
│ 应用层(Application) │
├─────────────────────────────────────────────┤
│ 框架层(Framework) │
│ - ArkUI 开发框架 │
│ - Ability 框架 │
│ - 分布式能力 │
├─────────────────────────────────────────────┤
│ 服务层(System Service) │
│ - 分布式软总线 │
│ - 分布式数据管理 │
│ - 分布式任务调度 │
├─────────────────────────────────────────────┤
│ 内核层(Kernel) │
│ - Linux 内核 │
│ - LiteOS 内核 │
│ - 鸿蒙微内核 │
└─────────────────────────────────────────────┘
关键特性:
DevEco Studio 是华为提供的鸿蒙应用开发官方IDE,基于 IntelliJ IDEA 社区版开发。
安装步骤:DevEco Studio 内置 SDK Manager,可以下载不同版本的鸿蒙 SDK:
Ability 是鸿蒙应用的基本组成单元,分为两种类型:
鸿蒙应用采用页面栈管理机制:
import router from '@ohos.router';
// 跳转到新页面
router.pushUrl({
url: 'pages/Index',
params: { id: 123 }
});
// 替换当前页面
router.replaceUrl({
url: 'pages/Detail'
});
// 返回上一页
router.back();
ArkTS 是鸿蒙应用开发的核心语言,基于 TypeScript 扩展而来。
基本语法示例:// 变量声明
let name: string = "HarmonyOS";
let version: number = 4.0;
let isStable: boolean = true;
// 常量声明
const BUNDLE_NAME = "com.example.myapp";
// 函数声明
function greet(name: string): string {
return `Hello, ${name}!`;
}
// 箭头函数
const add = (a: number, b: number): number => a + b;
// 类定义
class Person {
name: string;
age: number;
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
introduce(): string {
return `I am ${this.name}, ${this.age} years old`;
}
}
// 接口定义
interface User {
id: number;
name: string;
email: string;
}
// 枚举定义
enum Direction {
Up,
Down,
Left,
Right
}
ArkUI 提供了丰富的声明式UI组件:
@Entry
@Component
struct HelloWorld {
@State message: string = 'Hello World'
build() {
Column() {
Text(this.message)
.fontSize(30)
.fontWeight(FontWeight.Bold)
.margin({ bottom: 20 })
Button('点击我')
.width('80%')
.height(40)
.onClick(() => {
this.message = '你好,鸿蒙!';
})
Image('images/logo.png')
.width(100)
.height(100)
.margin({ top: 20 })
TextInput({ placeholder: '请输入内容' })
.width('90%')
.height(40)
.margin({ top: 20 })
.onChange((value: string) => {
console.log(`输入内容: ${value}`);
})
List({ space: 10 }) {
ForEach([1, 2, 3, 4, 5], (item: number) => {
ListItem() {
Text(`Item ${item}`)
.width('100%')
.height(50)
.textAlign(TextAlign.Center)
.backgroundColor('#f0f0f0')
}
})
}
.width('90%')
.height(200)
}
.width('100%')
.height('100%')
.justifyContent(FlexAlign.Center)
}
}
鸿蒙提供了多种状态装饰器来管理数据:
| 装饰器 | 说明 | 使用场景 |
|---|---|---|
| @State | 组件内部状态,变化触发UI刷新 | 页面内状态管理 |
| @Prop | 父组件向子组件单向传递 | 父子组件通信 |
| @Link | 父组件与子组件双向绑定 | 需要双向同步的场景 |
| @Provide/@Consume | 祖先与后代组件跨层级传递 | 跨层级状态共享 |
| @Observed/@Object | 对象级别的响应式 | 复杂对象状态监听 |
// @State 示例
@Entry
@Component
struct Counter {
@State count: number = 0;
build() {
Column() {
Text(`计数: ${this.count}`)
Button('增加')
.onClick(() => {
this.count++; // 自动触发UI更新
})
}
}
}
// @Prop 示例
@Component
struct ChildComponent {
@Prop message: string;
build() {
Text(this.message)
}
}
// @Link 示例
@Entry
@Component
struct ParentComponent {
@State count: number = 0;
build() {
Column() {
ChildWithLink({ count: $count }) // $ 表示双向绑定
}
}
}
@Component
struct ChildWithLink {
@Link count: number;
build() {
Button(`点击增加: ${this.count}`)
.onClick(() => {
this.count++; // 修改会同步到父组件
})
}
}
// @Provide/@Consume 示例
@Entry
@Component
struct GrandParent {
@Provide('theme') theme: string = 'dark';
build() {
Column() {
ParentComponent()
}
}
}
@Component
struct ParentComponent {
build() {
Column() {
ChildComponent()
}
}
}
@Component
struct ChildComponent {
@Consume('theme') theme: string;
build() {
Text(`当前主题: ${this.theme}`)
.backgroundColor(this.theme === 'dark' ? '#333' : '#fff')
}
}
// 在 Ability 中初始化
AppStorage.SetOrCreate('userToken', 'abc123');
AppStorage.SetOrCreate('userInfo', { name: '张三', age: 25 });
// 在组件中使用
@Entry
@Component
struct UserPage {
@StorageLink('userToken') userToken: string = '';
@StorageLink('userInfo') userInfo: object = {};
build() {
Column() {
Text(`Token: ${this.userToken}`)
Text(`姓名: ${this.userInfo.name}`)
}
}
}
// 监听变化
AppStorage.Has('userToken'); // 判断是否存在
AppStorage.Delete('userToken'); // 删除
AppStorage.Clear(); // 清空所有
LocalStorage:页面级存储,用于页面间参数传递
// 创建 LocalStorage
const storage = new LocalStorage();
storage.setOrCreate('pageData', { id: 1, name: '测试' });
// 在组件中使用
@Entry(storage)
@Component
struct StoragePage {
@LocalStorageLink('pageData') pageData: object = {};
build() {
Text(`数据: ${JSON.stringify(this.pageData)}`)
}
}
import http from '@ohos.net.http';
class HttpService {
// GET 请求
async get(url: string): Promise<string> {
const httpRequest = http.createHttp();
try {
const response = await httpRequest.request(url, {
method: http.RequestMethod.GET,
connectTimeout: 60000,
readTimeout: 60000,
header: {
'Content-Type': 'application/json'
}
});
return response.result as string;
} catch (error) {
console.error(`请求失败: ${JSON.stringify(error)}`);
throw error;
} finally {
httpRequest.destroy();
}
}
// POST 请求
async post(url: string, data: object): Promise<string> {
const httpRequest = http.createHttp();
try {
const response = await httpRequest.request(url, {
method: http.RequestMethod.POST,
connectTimeout: 60000,
readTimeout: 60000,
header: {
'Content-Type': 'application/json'
},
extraData: JSON.stringify(data)
});
return response.result as string;
} catch (error) {
console.error(`请求失败: ${JSON.stringify(error)}`);
throw error;
} finally {
httpRequest.destroy();
}
}
}
// 使用示例
const httpService = new HttpService();
const result = await httpService.get('https://api.example.com/data');
import webSocket from '@ohos.net.webSocket';
class WebSocketService {
private ws: webSocket.WebSocket;
constructor() {
this.ws = webSocket.createWebSocket();
}
connect(url: string): Promise<void> {
return new Promise((resolve, reject) => {
this.ws.on('open', () => {
console.log('WebSocket连接成功');
resolve();
});
this.ws.on('error', (error: Error) => {
console.error(`WebSocket错误: ${error.message}`);
reject(error);
});
this.ws.connect(url);
});
}
send(message: string): void {
this.ws.send(message);
}
onMessage(callback: (data: string) => void): void {
this.ws.on('message', (error: Error, data: string | ArrayBuffer) => {
if (!error && typeof data === 'string') {
callback(data);
}
});
}
close(): void {
this.ws.close();
}
}
import preferences from '@ohos.data.preferences';
class PrefService {
private prefs: preferences.Preferences;
constructor(context: Context, name: string) {
this.prefs = preferences.getPreferences(context, name);
}
// 存储数据
async set(key: string, value: string | number | boolean): Promise<void> {
await this.prefs.put(key, value);
await this.prefs.flush(); // 持久化存储
}
// 读取数据
async get(key: string, defaultValue: string | number | boolean): Promise<string | number | boolean> {
return await this.prefs.get(key, defaultValue);
}
// 删除数据
async delete(key: string): Promise<void> {
await this.prefs.delete(key);
await this.prefs.flush();
}
// 清空所有数据
async clear(): Promise<void> {
await this.prefs.clear();
await this.prefs.flush();
}
}
import relationalStore from '@ohos.data.relationalStore';
// 数据库配置
const config: relationalStore.StoreConfig = {
name: 'UserDB.db',
securityLevel: relationalStore.SecurityLevel.S1
};
// 建表SQL
const SQL_CREATE_TABLE = `
CREATE TABLE IF NOT EXISTS user (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
age INTEGER,
email TEXT UNIQUE
)
`;
class UserDB {
private store: relationalStore.RelationalStore;
constructor(store: relationalStore.RelationalStore) {
this.store = store;
}
// 初始化数据库
static async init(context: Context): Promise<UserDB> {
const store = await relationalStore.getRdbStore(context, config);
await store.executeSql(SQL_CREATE_TABLE);
return new UserDB(store);
}
// 插入数据
async insertUser(name: string, age: number, email: string): Promise<number> {
const values = {
name: name,
age: age,
email: email
};
return await this.store.insert('user', values);
}
// 查询数据
async queryUsers(): Promise<Array<{id: number, name: string, age: number, email: string}>> {
const predicates = new relationalStore.RdbPredicates('user');
const resultSet = await this.store.query(predicates, ['id', 'name', 'age', 'email']);
const users = [];
while (resultSet.goToNextRow()) {
users.push({
id: resultSet.getLong(resultSet.getColumnIndex('id')),
name: resultSet.getString(resultSet.getColumnIndex('name')),
age: resultSet.getLong(resultSet.getColumnIndex('age')),
email: resultSet.getString(resultSet.getColumnIndex('email'))
});
}
resultSet.close();
return users;
}
// 更新数据
async updateUser(id: number, name: string, age: number): Promise<number> {
const values = {
name: name,
age: age
};
const predicates = new relationalStore.RdbPredicates('user');
predicates.equalTo('id', id);
return await this.store.update(values, predicates);
}
// 删除数据
async deleteUser(id: number): Promise<number> {
const predicates = new relationalStore.RdbPredicates('user');
predicates.equalTo('id', id);
return await this.store.delete(predicates);
}
}
// 自定义按钮组件
@Component
struct CustomButton {
@Prop text: string = '按钮';
@Prop type: string = 'primary'; // primary, secondary, danger
@Prop disabled: boolean = false;
onAction: () => void = () => {}; // 回调函数
build() {
Button(this.text)
.width('100%')
.height(44)
.backgroundColor(this.getBackgroundColor())
.fontColor(this.disabled ? '#999' : '#fff')
.opacity(this.disabled ? 0.6 : 1)
.borderRadius(8)
.enabled(!this.disabled)
.onClick(() => {
if (!this.disabled) {
this.onAction();
}
})
}
private getBackgroundColor(): string {
if (this.disabled) return '#ccc';
switch (this.type) {
case 'primary': return '#007dff';
case 'secondary': return '#6c757d';
case 'danger': return '#dc3545';
default: return '#007dff';
}
}
}
// 使用自定义组件
@Entry
@Component
struct UseCustomButton {
build() {
Column({ space: 20 }) {
CustomButton({
text: '主要按钮',
type: 'primary',
onAction: () => {
console.log('点击了主要按钮');
}
})
CustomButton({
text: '危险按钮',
type: 'danger',
onAction: () => {
console.log('点击了危险按钮');
}
})
CustomButton({
text: '禁用按钮',
disabled: true,
onAction: () => {}
})
}
.width('100%')
.padding(20)
}
}
@Component
struct LifecycleComponent {
@State data: string = '';
// 组件即将创建时调用
aboutToAppear() {
console.log('组件即将创建');
// 初始化数据、订阅事件等
this.data = '初始化数据';
}
// 组件即将销毁时调用
aboutToDisappear() {
console.log('组件即将销毁');
// 清理资源、取消订阅等
}
// 页面显示时调用
onPageShow() {
console.log('页面显示');
}
// 页面隐藏时调用
onPageHide() {
console.log('页面隐藏');
}
// 页面返回时调用
onBackPress(): boolean | void {
console.log('返回键按下');
// 返回 true 表示已处理,不退出应用
return true;
}
build() {
Text(this.data)
}
}
@Entry
@Component
struct AnimationDemo {
@State opacityValue: number = 1.0;
@State scaleValue: number = 1.0;
@State rotateValue: number = 0;
@State translateValue: number = 0;
@State colorValue: string = '#007dff';
build() {
Column({ space: 30 }) {
// 透明度动画
Text('透明度动画')
.opacity(this.opacityValue)
.width(200)
.height(50)
.backgroundColor(this.colorValue)
// 缩放动画
Text('缩放动画')
.scale({ x: this.scaleValue, y: this.scaleValue })
.width(200)
.height(50)
.backgroundColor(this.colorValue)
// 旋转动画
Text('旋转动画')
.rotate({ angle: this.rotateValue })
.width(200)
.height(50)
.backgroundColor(this.colorValue)
// 平移动画
Text('平移动画')
.translate({ x: this.translateValue, y: 0 })
.width(200)
.height(50)
.backgroundColor(this.colorValue)
// 动画控制按钮
Row({ space: 10 }) {
Button('执行动画')
.onClick(() => {
// 使用 animateTo 实现动画
animateTo({ duration: 1000, curve: Curve.EaseInOut }, () => {
this.opacityValue = 0.2;
this.scaleValue = 1.5;
this.rotateValue = 360;
this.translateValue = 100;
this.colorValue = '#ff0000';
});
})
Button('重置')
.onClick(() => {
animateTo({ duration: 500 }, () => {
this.opacityValue = 1.0;
this.scaleValue = 1.0;
this.rotateValue = 0;
this.translateValue = 0;
this.colorValue = '#007dff';
});
})
}
}
.width('100%')
.height('100%')
.justifyContent(FlexAlign.Center)
}
}
@Entry
@Component
struct TransitionDemo {
@State isShow: boolean = true;
build() {
Column() {
// 条件渲染 + 转场动画
if (this.isShow) {
Text('转场动画示例')
.width(200)
.height(100)
.backgroundColor('#007dff')
.fontColor('#fff')
.textAlign(TextAlign.Center)
.transition({
type: TransitionType.Insert,
opacity: 0,
translate: { x: -100, y: 0 }
})
.transition({
type: TransitionType.Delete,
opacity: 0,
scale: { x: 0.5, y: 0.5 }
})
}
Button(this.isShow ? '隐藏' : '显示')
.margin({ top: 20 })
.onClick(() => {
animateTo({ duration: 300 }, () => {
this.isShow = !this.isShow;
});
})
}
.width('100%')
.height('100%')
.justifyContent(FlexAlign.Center)
}
}
@Entry
@Component
struct GestureDemo {
@State offsetX: number = 0;
@State offsetY: number = 0;
@State scaleValue: number = 1.0;
@State pinchValue: number = 1.0;
build() {
Column() {
Text('手势示例')
.width(200)
.height(200)
.backgroundColor('#007dff')
.fontColor('#fff')
.textAlign(TextAlign.Center)
.offset({ x: this.offsetX, y: this.offsetY })
.scale({ x: this.scaleValue * this.pinchValue, y: this.scaleValue * this.pinchValue })
// 拖拽手势
.gesture(
PanGesture()
.onActionStart(() => {
console.log('拖拽开始');
})
.onActionUpdate((event: GestureEvent) => {
this.offsetX += event.offsetX;
this.offsetY += event.offsetY;
})
.onActionEnd(() => {
console.log('拖拽结束');
})
)
// 缩放手势
.gesture(
PinchGesture()
.onActionUpdate((event: GestureEvent) => {
this.pinchValue = event.scale;
})
.onActionEnd(() => {
this.scaleValue *= this.pinchValue;
this.pinchValue = 1.0;
})
)
// 点击手势
.gesture(
TapGesture()
.onAction(() => {
console.log('点击');
})
)
// 长按手势
.gesture(
LongPressGesture()
.onAction(() => {
console.log('长按');
})
)
}
.width('100%')
.height('100%')
.justifyContent(FlexAlign.Center)
}
}
import deviceManager from '@ohos.distributedDeviceManager';
class DeviceService {
private dmInstance: deviceManager.DeviceManager;
constructor(context: Context) {
// 创建设备管理实例
this.dmInstance = deviceManager.createDeviceManager(context.bundleName);
}
// 获取可信设备列表
getTrustedDevices(): Array<deviceManager.DeviceInfo> {
return this.dmInstance.getTrustedDeviceListSync();
}
// 监听设备状态变化
onDeviceStateChange(callback: (deviceInfo: deviceManager.DeviceInfo) => void): void {
this.dmInstance.on('deviceStateChange', (result) => {
switch (result.action) {
case deviceManager.DeviceStateChangeAction.ONLINE:
console.log(`设备上线: ${result.device.deviceName}`);
break;
case deviceManager.DeviceStateChangeAction.OFFLINE:
console.log(`设备下线: ${result.device.deviceName}`);
break;
case deviceManager.DeviceStateChangeAction.INFO_UPDATE:
console.log(`设备信息更新: ${result.device.deviceName}`);
break;
}
callback(result.device);
});
}
// 停止监听
offDeviceStateChange(): void {
this.dmInstance.off('deviceStateChange');
}
}
import distributedData from '@ohos.data.distributedData;
class DistributedDataService {
private kvManager: distributedData.KVManager;
private kvStore: distributedData.KVStore;
constructor(context: Context) {
const config: distributedData.KVManagerConfig = {
bundleName: context.bundleName,
userInfo: {
userId: '0',
userType: distributedData.UserType.SAME_USER_ID
}
};
this.kvManager = distributedData.createKVManager(config);
}
// 创建KVStore
async createKVStore(storeId: string): Promise<void> {
const options: distributedData.Options = {
createIfMissing: true,
encrypt: false,
backup: false,
autoSync: true,
kvStoreType: distributedKvStoreType.DEVICE_COLLABORATION,
schema: undefined,
securityLevel: distributedData.SecurityLevel.S1
};
this.kvStore = await this.kvManager.getKVStore(storeId, options);
}
// 订阅数据变化
subscribeDataChange(): void {
this.kvStore.on('dataChange', distributedData.SubscribeType.SUBSCRIBE_TYPE_ALL, (data) => {
console.log(`数据变化: ${JSON.stringify(data)}`);
});
}
// 存储数据
async put(key: string, value: string | number | boolean | Uint8Array): Promise<void> {
await this.kvStore.put(key, value);
}
// 获取数据
async get(key: string): Promise<string | number | boolean | Uint8Array> {
return await this.kvStore.get(key);
}
// 删除数据
async delete(key: string): Promise<void> {
await this.kvStore.delete(key);
}
// 同步数据到其他设备
async sync(deviceIds: string[]): Promise<void> {
await this.kvStore.sync(deviceIds, distributedData.SyncMode.PUSH_PULL);
}
}
import distributedMissionManager from '@ohos.distributedMissionManager';
class MissionService {
// 继续在其他设备上运行
async continueMission(srcDeviceId: string, dstDeviceId: string, missionId: number): Promise<void> {
try {
await distributedMissionManager.continueMission({
srcDeviceId: srcDeviceId,
dstDeviceId: dstDeviceId,
missionId: missionId,
wantParam: {}
});
console.log('任务迁移成功');
} catch (error) {
console.error(`任务迁移失败: ${JSON.stringify(error)}`);
}
}
// 获取其他设备上的任务列表
async getMissions(deviceId: string): Promise<Array<distributedMissionManager.MissionInfo>> {
try {
const missions = await distributedMissionManager.getMissions(deviceId);
return missions;
} catch (error) {
console.error(`获取任务列表失败: ${JSON.stringify(error)}`);
return [];
}
}
}
import media from '@ohos.multimedia.media';
import audio from '@ohos.multimedia.audio';
class AudioPlayerService {
private avPlayer: media.AVPlayer;
constructor() {
this.avPlayer = media.createAVPlayer();
}
// 初始化播放器
async init(url: string): Promise<void> {
this.avPlayer.url = url;
// 监听状态变化
this.avPlayer.on('stateChange', (state: media.AVPlayerState) => {
console.log(`播放器状态: ${state}`);
});
// 监听错误
this.avPlayer.on('error', (error: media.MediaError) => {
console.error(`播放错误: ${JSON.stringify(error)}`);
});
// 监听播放完成
this.avPlayer.on('endOfStream', () => {
console.log('播放完成');
});
// 准备播放
await this.avPlayer.prepare();
}
// 播放
async play(): Promise<void> {
await this.avPlayer.play();
}
// 暂停
async pause(): Promise<void> {
await this.avPlayer.pause();
}
// 停止
async stop(): Promise<void> {
await this.avPlayer.stop();
}
// 跳转到指定位置
async seek(timeMs: number): Promise<void> {
await this.avPlayer.seek(timeMs);
}
// 获取当前播放时间
getCurrentTime(): number {
return this.avPlayer.currentTime;
}
// 获取总时长
getDuration(): number {
return this.avPlayer.duration;
}
// 释放资源
release(): void {
this.avPlayer.release();
}
}
import camera from '@ohos.multimedia.camera';
class CameraService {
private cameraManager: camera.CameraManager;
constructor(context: Context) {
this.cameraManager = camera.getCameraManager(context);
}
// 获取相机设备列表
getCameras(): Array<camera.CameraDevice> {
return this.cameraManager.getSupportedCameras();
}
// 获取支持的输出能力
getSupportedOutputCapability(cameraDevice: camera.CameraDevice): camera.CameraOutputCapability {
return this.cameraManager.getSupportedOutputCapability(cameraDevice);
}
// 创建预览输出
createPreviewOutput(profile: camera.Profile, surfaceId: string): camera.PreviewOutput {
const previewOutput = this.cameraManager.createPreviewOutput(profile, surfaceId);
return previewOutput;
}
// 创建拍照输出
createPhotoOutput(profile: camera.Profile): camera.PhotoOutput {
return this.cameraManager.createPhotoOutput(profile);
}
// 创建录像输出
createVideoOutput(profile: camera.Profile, surfaceId: string): camera.VideoOutput {
return this.cameraManager.createVideoOutput(profile, surfaceId);
}
// 创建相机输入
createCameraInput(cameraDevice: camera.CameraDevice): camera.CameraInput {
return this.cameraManager.createCameraInput(cameraDevice);
}
// 创建会话
createCaptureSession(): camera.CaptureSession {
return this.cameraManager.createCaptureSession();
}
}
import abilityAccessCtrl from '@ohos.abilityAccessCtrl';
class PermissionService {
// 检查权限
async checkPermission(context: Context, permission: string): Promise<boolean> {
const atManager = abilityAccessCtrl.createAtManager();
const grantStatus = await atManager.checkAccessToken(
context.applicationInfo.accessTokenId,
permission
);
return grantStatus === abilityAccessCtrl.GrantStatus.PERMISSION_GRANTED;
}
// 申请权限
async requestPermission(context: Context, permission: string): Promise<boolean> {
const atManager = abilityAccessCtrl.createAtManager();
const result = await atManager.requestPermissionsFromUser(context, [permission]);
return result.authResults[0] === 0;
}
// 申请多个权限
async requestPermissions(context: Context, permissions: string[]): Promise<boolean[]> {
const atManager = abilityAccessCtrl.createAtManager();
const result = await atManager.requestPermissionsFromUser(context, permissions);
return result.authResults.map(status => status === 0);
}
}
// 使用示例
const permissionService = new PermissionService();
const hasPermission = await permissionService.requestPermission(
context,
'ohos.permission.CAMERA'
);
import cryptoFramework from '@ohos.security.cryptoFramework';
class CryptoService {
// AES 加密
async aesEncrypt(plainText: string, key: string): Promise<string> {
// 创建对称密钥生成器
const keyGenerator = cryptoFramework.createSymKeyGenerator('AES128');
// 生成密钥
const keyData = new Uint8Array(16);
// 这里应该使用安全的随机数生成
for (let i = 0; i < 16; i++) {
keyData[i] = key.charCodeAt(i % key.length);
}
const symKey = await keyGenerator.convertKey({ data: keyData });
// 创建加密器
const cipher = cryptoFramework.createCipher('AES128|ECB|PKCS5');
// 初始化加密模式
await cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, symKey, null);
// 执行加密
const input = { data: new Uint8Array(Buffer.from(plainText)) };
const output = await cipher.doFinal(input);
return Buffer.from(output.data).toString('base64');
}
// AES 解密
async aesDecrypt(cipherText: string, key: string): Promise<string> {
// 创建对称密钥生成器
const keyGenerator = cryptoFramework.createSymKeyGenerator('AES128');
// 生成密钥
const keyData = new Uint8Array(16);
for (let i = 0; i < 16; i++) {
keyData[i] = key.charCodeAt(i % key.length);
}
const symKey = await keyGenerator.convertKey({ data: keyData });
// 创建解密器
const cipher = cryptoFramework.createCipher('AES128|ECB|PKCS5');
// 初始化解密模式
await cipher.init(cryptoFramework.CryptoMode.DECRYPT_MODE, symKey, null);
// 执行解密
const input = { data: new Uint8Array(Buffer.from(cipherText, 'base64')) };
const output = await cipher.doFinal(input);
return Buffer.from(output.data).toString('utf-8');
}
}
// 1. 避免在 build 方法中执行耗时操作
@Component
struct BadExample {
@State data: string[] = [];
build() {
// ❌ 错误:在 build 中执行耗时操作
const processedData = this.data.map(item => {
// 复杂计算
return item.toUpperCase();
});
List() {
ForEach(processedData, (item: string) => {
ListItem() {
Text(item)
}
})
}
}
}
@Component
struct GoodExample {
@State data: string[] = [];
@State processedData: string[] = [];
aboutToAppear() {
// ✅ 正确:在生命周期中预处理数据
this.processedData = this.data.map(item => item.toUpperCase());
}
build() {
List() {
ForEach(this.processedData, (item: string) => {
ListItem() {
Text(item)
}
})
}
}
}
// 2. 使用 LazyForEach 优化长列表
@Entry
@Component
struct LazyListDemo {
private data: MyDataSource = new MyDataSource();
aboutToAppear() {
for (let i = 0; i < 1000; i++) {
this.data.pushData(`Item ${i}`);
}
}
build() {
List({ space: 10 }) {
LazyForEach(this.data, (item: string) => {
ListItem() {
Text(item)
.width('100%')
.height(50)
.backgroundColor('#f0f0f0')
}
}, (item: string) => item) // 唯一标识
}
.width('100%')
.height('100%')
}
}
class MyDataSource implements IDataSource {
private dataArray: string[] = [];
private listeners: DataChangeListener[] = [];
pushData(item: string): void {
this.dataArray.push(item);
this.notifyDataAdd(this.dataArray.length - 1);
}
totalCount(): number {
return this.dataArray.length;
}
getData(index: number): string {
return this.dataArray[index];
}
registerDataChangeListener(listener: DataChangeListener): void {
if (this.listeners.indexOf(listener) < 0) {
this.listeners.push(listener);
}
}
unregisterDataChangeListener(listener: DataChangeListener): void {
const index = this.listeners.indexOf(listener);
if (index >= 0) {
this.listeners.splice(index, 1);
}
}
notifyDataAdd(index: number): void {
this.listeners.forEach(listener => {
listener.onDataAdd(index);
});
}
notifyDataChange(index: number): void {
this.listeners.forEach(listener => {
listener.onDataChange(index);
});
}
notifyDataDelete(index: number): void {
this.listeners.forEach(listener => {
listener.onDataDelete(index);
});
}
}
// 1. 及时释放资源
class ResourceManager {
private resources: Array<{ id: string; release: () => void }> = [];
addResource(id: string, release: () => void): void {
this.resources.push({ id, release });
}
releaseAll(): void {
this.resources.forEach(resource => {
resource.release();
});
this.resources = [];
}
}
// 2. 避免内存泄漏
@Component
struct MemoryLeakExample {
private timer: number = -1;
aboutToAppear() {
// ❌ 错误:定时器未清理
this.timer = setInterval(() => {
console.log('定时任务');
}, 1000);
}
aboutToDisappear() {
// ✅ 正确:清理定时器
if (this.timer !== -1) {
clearInterval(this.timer);
this.timer = -1;
}
}
build() {
Text('内存管理示例')
}
}
// 3. 使用 WeakRef 避免循环引用
class Node {
value: number;
next: WeakRef<Node> | null = null;
constructor(value: number) {
this.value = value;
}
}
// 1. 延迟加载非关键资源
@Entry
@Component
struct LazyLoadDemo {
@State isReady: boolean = false;
async aboutToAppear() {
// 延迟加载非关键资源
setTimeout(() => {
this.loadNonCriticalResources();
}, 1000);
}
private loadNonCriticalResources(): void {
// 加载非关键资源
this.isReady = true;
}
build() {
Column() {
if (this.isReady) {
Text('非关键资源已加载')
} else {
LoadingProgress()
.width(50)
.height(50)
}
}
}
}
// 2. 使用 Worker 处理耗时任务
import worker from '@ohos.worker';
class WorkerService {
private workerInstance: worker.ThreadWorker;
constructor() {
this.workerInstance = new worker.ThreadWorker('entry/workers/MyWorker.ts');
}
// 发送消息到 Worker
postMessage(message: object): void {
this.workerInstance.postMessage(message);
}
// 接收 Worker 消息
onMessage(callback: (data: any) => void): void {
this.workerInstance.onmessage = (event: worker.MessageEvents) => {
callback(event.data);
};
}
// 终止 Worker
terminate(): void {
this.workerInstance.terminate();
}
}
// MyWorker.ts
import worker from '@ohos.worker';
const workerPort = worker.workerPort;
workerPort.onmessage = (event: worker.MessageEvents) => {
// 执行耗时任务
const result = heavyComputation(event.data);
workerPort.postMessage(result);
};
function heavyComputation(data: any): any {
// 复杂计算
return data;
}
import nativeRender from '@ohos.nativeRender';
import { XComponentContext, XComponentSurfaceSizeChangeCallback } from '@ohos.nativeRender';
@Entry
@Component
struct XComponentDemo {
private xComponentContext: XComponentContext | null = null;
build() {
Column() {
XComponent('xcomponent', {
id: 'xcomponent',
type: 'surface',
libraryname: 'native_render'
})
.onLoad((context: XComponentContext) => {
this.xComponentContext = context;
this.initRender();
})
.onDestroy(() => {
this.releaseRender();
})
.width('100%')
.height('50%')
}
.width('100%')
.height('100%')
}
private initRender(): void {
if (this.xComponentContext) {
// 初始化渲染环境
this.xComponentContext.surfaceSizeChangeCallback = (width: number, height: number) => {
console.log(`Surface size changed: ${width}x${height}`);
};
}
}
private releaseRender(): void {
// 释放渲染资源
}
}
// native_hello.cpp
#include <napi/native_api.h>
#include <hilog/log.h>
// 日志宏
#define LOG_PRINT_DOMAIN 0x0001
#define LOG_TAG "NativeDemo"
// 导出函数
static napi_value Add(napi_env env, napi_callback_info info) {
size_t argc = 2;
napi_value args[2];
napi_get_cb_info(env, info, &argc, args, nullptr, nullptr);
double value1, value2;
napi_get_value_double(env, args[0], &value1);
napi_get_value_double(env, args[1], &value2);
napi_value result;
napi_create_double(env, value1 + value2, &result);
OH_LOG_Print(LOG_APP, LOG_INFO, LOG_PRINT_DOMAIN, LOG_TAG, "Add function called");
return result;
}
// 模块初始化
EXTERN_C_START
static napi_value Init(napi_env env, napi_value exports) {
napi_property_descriptor desc[] = {
{ "Add", nullptr, Add, nullptr, nullptr, nullptr, napi_default, nullptr }
};
napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc);
return exports;
}
EXTERN_C_END
static napi_module demoModule = {
.nm_version = 1,
.nm_flags = 0,
.nm_filename = nullptr,
.nm_register_func = Init,
.nm_modname = "nativehello",
.nm_priv = ((void*)0),
.reserved = { 0 },
};
extern "C" __attribute__((constructor)) void RegisterNativehelloModule(void) {
napi_module_register(&demoModule);
}
// 导入 Native 模块
import native from 'libnativehello.so';
@Entry
@Component
struct NativeCallDemo {
@State result: number = 0;
build() {
Column() {
Text(`计算结果: ${this.result}`)
.fontSize(20)
.margin({ bottom: 20 })
Button('调用 Native 函数')
.onClick(() => {
// 调用 Native 函数
this.result = native.Add(10, 20);
})
}
.width('100%')
.height('100%')
.justifyContent(FlexAlign.Center)
}
}
// test/ExampleTest.ts
import { describe, it, expect } from '@ohos/hypium';
export default function exampleTest() {
describe('ExampleTest', () => {
it('should add two numbers correctly', 0, () => {
const result = add(1, 2);
expect(result).assertEqual(3);
});
it('should handle negative numbers', 0, () => {
const result = add(-1, -2);
expect(result).assertEqual(-3);
});
it('should handle zero', 0, () => {
const result = add(0, 5);
expect(result).assertEqual(5);
});
});
}
function add(a: number, b: number): number {
return a + b;
}
// test/UITest.ts
import { describe, it, beforeAll, expect } from '@ohos/hypium';
import { abilityDelegatorRegistry } from '@ohos.app.ability.abilityDelegatorRegistry';
export default function uiTest() {
describe('UITest', () => {
beforeAll(() => {
// 测试前准备
});
it('should display correct text', 0, () => {
const abilityDelegator = abilityDelegatorRegistry.getAbilityDelegator();
// 获取当前页面并验证UI元素
});
});
}
HarmonyOS 的核心特性包括:
| 对比维度 | FA 模型 | Stage 模型 |
|---|---|---|
| 应用组件 | Feature Ability + Particle Ability | UIAbility + ExtensionAbility |
| 生命周期 | 页面级生命周期 | Ability级生命周期 |
| 上下文 | PageAbilityContext | UIAbilityContext |
| 窗口管理 | 无独立窗口概念 | 支持多窗口和场景化 |
| 分布式能力 | 基础支持 | 增强支持 |
| 推荐使用 | 已停止更新 | 官方推荐 |
鸿蒙应用的基本组成单元是 Ability,分为以下类型:
Create → Foreground → Background → Destroy
ArkTS 是基于 TypeScript 扩展而来的编程语言,专门为鸿蒙应用开发设计。
关系:| 对比维度 | TypeScript | ArkTS |
|---|---|---|
| UI开发 | 需要配合框架 | 内置声明式UI |
| 状态管理 | 需要第三方库 | 内置装饰器支持 |
| 运行时 | JavaScript 引擎 | 方舟编译运行时 |
| 性能 | JavaScript 解释执行 | 静态编译优化 |
| 并发模型 | 单线程 | 支持多线程 |
Create → WindowStageCreate → Foreground → Background → WindowStageDestroy → Destroy
各状态说明:
onCreate()onWindowStageCreate()onForeground()onBackground()onWindowStageDestroy()onDestroy()export default class EntryAbility extends UIAbility {
onCreate(want: Want, launchParam: Constant.LaunchParam): void {
console.log('Ability创建');
}
onWindowStageCreate(windowStage: window.WindowStage): void {
console.log('窗口阶段创建');
windowStage.loadContent('pages/Index', (err, data) => {
if (err.code) {
console.error(`加载页面失败: ${JSON.stringify(err)}`);
return;
}
console.log('页面加载成功');
});
}
onForeground(): void {
console.log('应用进入前台');
}
onBackground(): void {
console.log('应用进入后台');
}
onWindowStageDestroy(): void {
console.log('窗口阶段销毁');
}
onDestroy(): void {
console.log('Ability销毁');
}
}
面试官视角: 考察候选人对鸿蒙应用运行机制的掌握,能否正确处理各生命周期阶段的操作。
鸿蒙提供了丰富的状态管理装饰器,满足不同场景的需求:
@Entry
@Component
struct Counter {
@State count: number = 0; // 组件内部状态
build() {
Column() {
Text(`计数: ${this.count}`)
Button('增加')
.onClick(() => {
this.count++; // 修改后自动刷新UI
})
}
}
}
适用场景:组件内部状态管理,变化触发当前组件重新渲染。
@Component
struct ChildComponent {
@Prop message: string; // 从父组件接收,单向绑定
build() {
Text(this.message)
}
}
@Entry
@Component
struct Parent {
@State msg: string = 'Hello';
build() {
ChildComponent({ message: this.msg })
}
}
适用场景:父组件向子组件传递数据,子组件不能修改。
@Component
struct ChildComponent {
@Link count: number; // 与父组件双向绑定
build() {
Button(`点击增加: ${this.count}`)
.onClick(() => {
this.count++; // 修改会同步到父组件
})
}
}
@Entry
@Component
struct Parent {
@State count: number = 0;
build() {
Column() {
Text(`父组件计数: ${this.count}`)
ChildComponent({ count: this.count }) // 传递双向绑定
}
}
}
适用场景:需要父子组件双向同步数据的场景。
@Entry
@Component
struct GrandParent {
@Provide('theme') theme: string = 'dark'; // 提供状态
build() {
Column() {
ParentComponent()
}
}
}
@Component
struct ParentComponent {
build() {
Column() {
ChildComponent()
}
}
}
@Component
struct ChildComponent {
@Consume('theme') theme: string; // 消费祖先提供的状态
build() {
Text(`当前主题: ${this.theme}`)
.backgroundColor(this.theme === 'dark' ? '#333' : '#fff')
}
}
适用场景:跨多层级组件共享状态,避免逐层传递。
@Observed
class User {
name: string;
age: number;
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
}
@Component
struct UserComponent {
@ObjectLink user: User;
build() {
Column() {
Text(`姓名: ${this.user.name}`)
Text(`年龄: ${this.user.age}`)
}
}
}
适用场景:复杂对象的属性变化监听。
// AppStorage - 应用全局状态
AppStorage.SetOrCreate('userToken', 'abc123');
@Entry
@Component
struct UserPage {
@StorageLink('userToken') userToken: string = '';
build() {
Text(`Token: ${this.userToken}`)
}
}
适用场景:页面间共享数据、持久化存储。
面试官视角: 考察候选人对状态管理的全面理解,能否根据场景选择合适的状态管理方式。
鸿蒙提供了两种主要的页面跳转方式:
import router from '@ohos.router';
// 跳转到新页面并传递参数
router.pushUrl({
url: 'pages/Detail',
params: {
id: 123,
name: '测试商品',
price: 99.99
}
});
// 替换当前页面(当前页面会被销毁)
router.replaceUrl({
url: 'pages/Login'
});
// 返回上一页
router.back();
// 返回指定页面
router.back('pages/Index');
// 清除页面栈(保留当前页面,清除其他所有页面)
router.clear();
// 获取页面栈长度
const stackLength = router.getLength();
接收参数:
@Entry
@Component
struct DetailPage {
@State id: number = 0;
@State name: string = '';
@State price: number = 0;
aboutToAppear() {
const params = router.getParams() as Record<string, Object>;
this.id = params.id as number;
this.name = params.name as string;
this.price = params.price as number;
}
build() {
Column() {
Text(`ID: ${this.id}`)
Text(`名称: ${this.name}`)
Text(`价格: ${this.price}`)
}
}
}
@Entry
@Component
struct NavigationDemo {
navPathStack: NavPathStack = new NavPathStack();
build() {
Navigation(this.navPathStack) {
Column() {
Button('跳转到详情')
.onClick(() => {
this.navPathStack.pushPathByName('Detail', null);
})
}
}
.title('首页')
.mode(NavigationMode.Stack)
}
}
@Builder
export function DetailPageBuilder() {
DetailPage()
}
@Component
struct DetailPage {
build() {
NavDestination() {
Column() {
Text('详情页')
}
}
.title('详情')
}
}
两种方式的对比:
| 对比维度 | router | Navigation |
|---|---|---|
| 使用方式 | 命令式 | 声明式 |
| 页面栈管理 | 手动管理 | 自动管理 |
| 转场动画 | 需要自定义 | 内置支持 |
| 复杂导航 | 较难支持 | 天然支持 |
| 推荐使用 | 简单场景 | 复杂场景 |
分布式软总线是HarmonyOS的核心技术之一,为设备之间的互联互通提供统一的通信基座。
分布式软总线是"连接鸿蒙生态设备的基石",它将多种通信方式(如Wi-Fi、蓝牙、NFC等)统一封装,为上层应用提供透明的连接能力。
┌─────────────────────────────────────────────┐
│ 应用层(分布式能力) │
├─────────────────────────────────────────────┤
│ 分布式软总线(Foundation) │
│ ┌─────────┬─────────┬─────────┐ │
│ │ 发现 │ 连接 │ 传输 │ │
│ │ 模块 │ 模块 │ 模块 │ │
│ └─────────┴─────────┴─────────┘ │
├─────────────────────────────────────────────┤
│ 协议栈(Wi-Fi/BLE/NFC) │
└─────────────────────────────────────────────┘
鸿蒙提供了 @ohos.net.http 模块进行HTTP网络请求。
import http from '@ohos.net.http';
class HttpManager {
private static instance: HttpManager;
static getInstance(): HttpManager {
if (!HttpManager.instance) {
HttpManager.instance = new HttpManager();
}
return HttpManager.instance;
}
// GET 请求
async get<T>(url: string, params?: Record<string, string>): Promise<T> {
const httpRequest = http.createHttp();
try {
let fullUrl = url;
if (params) {
const queryString = Object.keys(params)
.map(key => `${key}=${encodeURIComponent(params[key])}`)
.join('&');
fullUrl += `?${queryString}`;
}
const response = await httpRequest.request(fullUrl, {
method: http.RequestMethod.GET,
connectTimeout: 60000,
readTimeout: 60000,
header: {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
});
if (response.responseCode === 200) {
return JSON.parse(response.result as string) as T;
} else {
throw new Error(`HTTP Error: ${response.responseCode}`);
}
} catch (error) {
console.error(`请求失败: ${JSON.stringify(error)}`);
throw error;
} finally {
httpRequest.destroy();
}
}
// POST 请求
async post<T>(url: string, data: object): Promise<T> {
const httpRequest = http.createHttp();
try {
const response = await httpRequest.request(url, {
method: http.RequestMethod.POST,
connectTimeout: 60000,
readTimeout: 60000,
header: {
'Content-Type': 'application/json',
'Accept': 'application/json'
},
extraData: JSON.stringify(data)
});
if (response.responseCode === 200) {
return JSON.parse(response.result as string) as T;
} else {
throw new Error(`HTTP Error: ${response.responseCode}`);
}
} catch (error) {
console.error(`请求失败: ${JSON.stringify(error)}`);
throw error;
} finally {
httpRequest.destroy();
}
}
}
在 module.json5 中添加网络权限:
{
"module": {
"requestPermissions": [
{
"name": "ohos.permission.INTERNET"
}
]
}
}
面试官视角: 考察候选人对网络编程的掌握程度,能否处理实际的网络请求场景。
鸿蒙提供了多种本地数据存储方式:
import preferences from '@ohos.data.preferences';
class PrefService {
private prefs: preferences.Preferences;
constructor(context: Context, name: string = 'default') {
this.prefs = preferences.getPreferences(context, name);
}
async set<T extends preferences.ValueType>(key: string, value: T): Promise<void> {
await this.prefs.put(key, value);
await this.prefs.flush();
}
async get<T extends preferences.ValueType>(key: string, defaultValue: T): Promise<T> {
return await this.prefs.get(key, defaultValue) as T;
}
async delete(key: string): Promise<void> {
await this.prefs.delete(key);
await this.prefs.flush();
}
async clear(): Promise<void> {
await this.prefs.clear();
await this.prefs.flush();
}
}
import relationalStore from '@ohos.data.relationalStore';
const config: relationalStore.StoreConfig = {
name: 'UserDB.db',
securityLevel: relationalStore.SecurityLevel.S1
};
const SQL_CREATE_USER_TABLE = `
CREATE TABLE IF NOT EXISTS user (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
age INTEGER,
email TEXT UNIQUE
)
`;
class UserDB {
private store: relationalStore.RelationalStore;
static async init(context: Context): Promise<UserDB> {
const store = await relationalStore.getRdbStore(context, config);
await store.executeSql(SQL_CREATE_USER_TABLE);
return new UserDB(store);
}
async insertUser(user: { name: string; age: number; email: string }): Promise<number> {
return await this.store.insert('user', user);
}
async queryUsers(): Promise<Array<{id: number; name: string; age: number; email: string}>> {
const predicates = new relationalStore.RdbPredicates('user');
const resultSet = await this.store.query(predicates, ['id', 'name', 'age', 'email']);
const users = [];
while (resultSet.goToNextRow()) {
users.push({
id: resultSet.getLong(resultSet.getColumnIndex('id')),
name: resultSet.getString(resultSet.getColumnIndex('name')),
age: resultSet.getLong(resultSet.getColumnIndex('age')),
email: resultSet.getString(resultSet.getColumnIndex('email'))
});
}
resultSet.close();
return users;
}
}
import distributedData from '@ohos.data.distributedData';
class DistributedDataService {
private kvManager: distributedData.KVManager;
private kvStore: distributedData.KVStore;
constructor(context: Context) {
const config: distributedData.KVManagerConfig = {
bundleName: context.bundleName,
userInfo: { userId: '0', userType: distributedData.UserType.SAME_USER_ID }
};
this.kvManager = distributedData.createKVManager(config);
}
async createKVStore(storeId: string): Promise<void> {
const options: distributedData.Options = {
createIfMissing: true,
encrypt: false,
backup: false,
autoSync: true,
kvStoreType: distributedData.KVStoreType.DEVICE_COLLABORATION,
securityLevel: distributedData.SecurityLevel.S1
};
this.kvStore = await this.kvManager.getKVStore(storeId, options);
}
async put(key: string, value: string | number | boolean | Uint8Array): Promise<void> {
await this.kvStore.put(key, value);
}
async get(key: string): Promise<string | number | boolean | Uint8Array> {
return await this.kvStore.get(key);
}
async sync(deviceIds: string[]): Promise<void> {
await this.kvStore.sync(deviceIds, distributedData.SyncMode.PUSH_PULL);
}
}
| 存储方式 | 适用场景 | 优点 | 缺点 |
|---|---|---|---|
| Preferences | 简单配置 | 使用简单、性能好 | 不支持复杂查询 |
| RDB | 结构化数据 | 支持复杂查询、事务 | 使用较复杂 |
| 分布式KV | 跨设备同步 | 自动同步、高可用 | 数据量有限 |
鸿蒙提供了多种动画实现机制:
@Entry
@Component
struct PropertyAnimationDemo {
@State opacityValue: number = 1.0;
@State scaleValue: number = 1.0;
@State rotateValue: number = 0;
@State translateValue: number = 0;
build() {
Column({ space: 30 }) {
Text('属性动画')
.opacity(this.opacityValue)
.scale({ x: this.scaleValue, y: this.scaleValue })
.rotate({ angle: this.rotateValue })
.translate({ x: this.translateValue, y: 0 })
.width(200)
.height(50)
.backgroundColor('#007dff')
.fontColor('#fff')
.textAlign(TextAlign.Center)
Button('执行动画')
.onClick(() => {
animateTo({
duration: 1000,
curve: Curve.EaseInOut,
iterations: 1,
playMode: PlayMode.Normal
}, () => {
this.opacityValue = 0.2;
this.scaleValue = 1.5;
this.rotateValue = 360;
this.translateValue = 100;
});
})
}
.width('100%')
.height('100%')
.justifyContent(FlexAlign.Center)
}
}
@Entry
@Component
struct TransitionDemo {
@State isShow: boolean = true;
build() {
Column() {
if (this.isShow) {
Text('转场动画')
.width(200)
.height(100)
.backgroundColor('#007dff')
.fontColor('#fff')
.textAlign(TextAlign.Center)
.transition({
type: TransitionType.Insert,
opacity: 0,
translate: { x: -100, y: 0 },
scale: { x: 0.5, y: 0.5 }
})
.transition({
type: TransitionType.Delete,
opacity: 0,
rotate: { angle: 90 }
})
}
Button(this.isShow ? '隐藏' : '显示')
.margin({ top: 20 })
.onClick(() => {
animateTo({ duration: 300 }, () => {
this.isShow = !this.isShow;
});
})
}
.width('100%')
.height('100%')
.justifyContent(FlexAlign.Center)
}
}
鸿蒙提供了丰富的手势识别和处理能力:
@Entry
@Component
struct GestureDemo {
@State tapCount: number = 0;
@State longPressCount: number = 0;
@State doubleTapCount: number = 0;
build() {
Column({ space: 20 }) {
Text('基础手势')
.width(200)
.height(100)
.backgroundColor('#007dff')
.fontColor('#fff')
.textAlign(TextAlign.Center)
.gesture(
TapGesture()
.onAction(() => {
this.tapCount++;
})
)
Text('双击手势')
.width(200)
.height(100)
.backgroundColor('#28a745')
.fontColor('#fff')
.textAlign(TextAlign.Center)
.gesture(
TapGesture({ count: 2 })
.onAction(() => {
this.doubleTapCount++;
})
)
Text('长按手势')
.width(200)
.height(100)
.backgroundColor('#dc3545')
.fontColor('#fff')
.textAlign(TextAlign.Center)
.gesture(
LongPressGesture({ repeat: true })
.onAction(() => {
this.longPressCount++;
})
)
Text(`单击: ${this.tapCount} | 双击: ${this.doubleTapCount} | 长按: ${this.longPressCount}`)
}
.width('100%')
.height('100%')
.justifyContent(FlexAlign.Center)
}
}
@Entry
@Component
struct PanGestureDemo {
@State offsetX: number = 0;
@State offsetY: number = 0;
@State startX: number = 0;
@State startY: number = 0;
build() {
Column() {
Text('拖拽我')
.offset({ x: this.offsetX, y: this.offsetY })
.width(100)
.height(100)
.backgroundColor('#007dff')
.fontColor('#fff')
.textAlign(TextAlign.Center)
.gesture(
PanGesture()
.onActionStart(() => {
this.startX = this.offsetX;
this.startY = this.offsetY;
})
.onActionUpdate((event: GestureEvent) => {
this.offsetX = this.startX + event.offsetX;
this.offsetY = this.startY + event.offsetY;
})
)
}
.width('100%')
.height('100%')
.justifyContent(FlexAlign.Center)
}
}
@Entry
@Component
struct PinchGestureDemo {
@State scaleValue: number = 1.0;
@State baseScale: number = 1.0;
build() {
Column() {
Text('缩放手势')
.scale({ x: this.scaleValue, y: this.scaleValue })
.width(200)
.height(200)
.backgroundColor('#007dff')
.fontColor('#fff')
.textAlign(TextAlign.Center)
.gesture(
PinchGesture()
.onActionStart(() => {
this.baseScale = this.scaleValue;
})
.onActionUpdate((event: GestureEvent) => {
this.scaleValue = this.baseScale * event.scale;
if (this.scaleValue < 0.5) this.scaleValue = 0.5;
if (this.scaleValue > 3) this.scaleValue = 3;
})
)
}
.width('100%')
.height('100%')
.justifyContent(FlexAlign.Center)
}
}
@Entry
@Component
struct CombinedGestureDemo {
build() {
Column() {
Text('组合手势')
.width(200)
.height(200)
.backgroundColor('#007dff')
.fontColor('#fff')
.textAlign(TextAlign.Center)
.gesture(
GestureGroup(GestureMode.Parallel, [
TapGesture()
.onAction(() => {
console.log('Tap');
}),
LongPressGesture()
.onAction(() => {
console.log('LongPress');
})
])
)
}
.width('100%')
.height('100%')
.justifyContent(FlexAlign.Center)
}
}
面试官视角: 考察候选人对移动端手势处理的理解,能否创建自然流畅的交互体验。
// 避免在 build 方法中执行耗时操作
@Component
struct GoodExample {
@State data: string[] = [];
@State processedData: string[] = [];
aboutToAppear() {
// ✅ 正确:在生命周期中预处理数据
this.processedData = this.data.map(item => item.toUpperCase());
}
build() {
List() {
ForEach(this.processedData, (item: string) => {
ListItem() {
Text(item)
}
})
}
}
}
// 使用 LazyForEach 优化长列表
@Entry
@Component
struct LazyListDemo {
private data: MyDataSource = new MyDataSource();
aboutToAppear() {
for (let i = 0; i < 1000; i++) {
this.data.pushData(`Item ${i}`);
}
}
build() {
List({ space: 10 }) {
LazyForEach(this.data, (item: string) => {
ListItem() {
Text(item)
.width('100%')
.height(50)
.backgroundColor('#f0f0f0')
}
}, (item: string) => item)
}
.width('100%')
.height('100%')
}
}
// 及时释放资源
class ResourceManager {
private resources: Array<{ id: string; release: () => void }> = [];
addResource(id: string, release: () => void): void {
this.resources.push({ id, release });
}
releaseAll(): void {
this.resources.forEach(resource => {
resource.release();
});
this.resources = [];
}
}
// 避免内存泄漏
@Component
struct MemoryLeakExample {
private timer: number = -1;
aboutToAppear() {
this.timer = setInterval(() => {
console.log('定时任务');
}, 1000);
}
aboutToDisappear() {
if (this.timer !== -1) {
clearInterval(this.timer);
this.timer = -1;
}
}
build() {
Text('内存管理示例')
}
}
// 延迟加载非关键资源
@Entry
@Component
struct LazyLoadDemo {
@State isReady: boolean = false;
async aboutToAppear() {
setTimeout(() => {
this.loadNonCriticalResources();
}, 1000);
}
private loadNonCriticalResources(): void {
this.isReady = true;
}
build() {
Column() {
if (this.isReady) {
Text('非关键资源已加载')
} else {
LoadingProgress()
.width(50)
.height(50)
}
}
}
}
// 请求合并、缓存、重试机制
class NetworkOptimizer {
private cache: Map<string, { data: any; timestamp: number }> = new Map();
private pendingRequests: Map<string, Promise<any>> = new Map();
async requestWithCache<T>(url: string, options?: {
cacheTime?: number;
retryCount?: number;
}): Promise<T> {
const cacheTime = options?.cacheTime || 60000;
const retryCount = options?.retryCount || 3;
// 检查缓存
const cached = this.cache.get(url);
if (cached && Date.now() - cached.timestamp < cacheTime) {
return cached.data;
}
// 检查是否有正在进行的请求
const pending = this.pendingRequests.get(url);
if (pending) {
return pending;
}
// 发起新请求
const request = this.doRequest<T>(url, retryCount);
this.pendingRequests.set(url, request);
try {
const result = await request;
this.cache.set(url, { data: result, timestamp: Date.now() });
return result;
} finally {
this.pendingRequests.delete(url);
}
}
private async doRequest<T>(url: string, retryCount: number): Promise<T> {
let lastError: Error | null = null;
for (let i = 0; i < retryCount; i++) {
try {
const response = await fetch(url);
if (response.ok) {
return await response.json();
}
} catch (error) {
lastError = error as Error;
}
}
throw lastError || new Error('Request failed');
}
}
面试官视角: 考察候选人对性能优化的理解和实践经验,能否综合应用多种优化手段。
鸿蒙提供了多种并发编程方式:
import taskpool from '@ohos.taskpool';
@Concurrent
function calculateSum(start: number, end: number): number {
let sum = 0;
for (let i = start; i <= end; i++) {
sum += i;
}
return sum;
}
class TaskPoolService {
async executeTask<T>(task: taskpool.Task): Promise<T> {
try {
const result = await taskpool.execute(task);
return result as T;
} catch (error) {
console.error(`任务执行失败: ${JSON.stringify(error)}`);
throw error;
}
}
async executeGroup<T>(group: taskpool.TaskGroup): Promise<T[]> {
try {
const results = await taskpool.executeGroup(group);
return results as T[];
} catch (error) {
console.error(`任务组执行失败: ${JSON.stringify(error)}`);
throw error;
}
}
}
// 使用示例
const taskPoolService = new TaskPoolService();
const sumTask = new taskpool.Task(calculateSum, 1, 1000000);
const result = await taskPoolService.executeTask<number>(sumTask);
console.log(`计算结果: ${result}`);
// main.ts(主线程)
import worker from '@ohos.worker';
class WorkerService {
private workerInstance: worker.ThreadWorker;
private messageCallbacks: Map<string, (data: any) => void> = new Map[];
constructor(workerUrl: string) {
this.workerInstance = new worker.ThreadWorker(workerUrl);
this.workerInstance.onmessage = (event: worker.MessageEvents) => {
const { type, data } = event.data;
const callback = this.messageCallbacks.get(type);
if (callback) {
callback(data);
}
};
}
postMessage(type: string, data: any): void {
this.workerInstance.postMessage({ type, data });
}
onMessage(type: string, callback: (data: any) => void): void {
this.messageCallbacks.set(type, callback);
}
terminate(): void {
this.workerInstance.terminate();
}
}
// workers/MyWorker.ts(Worker线程)
import worker from '@ohos.worker';
const workerPort = worker.workerPort;
workerPort.onmessage = (event: worker.MessageEvents) => {
const { type, data } = event.data;
switch (type) {
case 'calculate':
const result = heavyCalculation(data.start, data.end);
workerPort.postMessage({ type: 'result', data: result });
break;
case 'process':
const processed = processData(data);
workerPort.postMessage({ type: 'result', data: processed });
break;
}
};
function heavyCalculation(start: number, end: number): number {
let sum = 0;
const total = end - start + 1;
for (let i = start; i <= end; i++) {
sum += i;
// 每10%报告一次进度
if (i % Math.floor(total / 10) === 0) {
workerPort.postMessage({
type: 'progress',
data: Math.floor((i - start) / total * 100)
});
}
}
return sum;
}
function processData(data: number[]): number[] {
return data.map(item => {
// 模拟耗时计算
for (let i = 0; i < 1000; i++) {
Math.sqrt(item);
}
return item * 2;
});
}
// build-profile.json5
{
"app": {
"products": [
{
"name": "default",
"signingConfig": "default",
"compatibleSdkVersion": "4.0.0(10)",
"runtimeOS": "HarmonyOS"
}
],
"buildModeSet": [
{
"name": "debug"
},
{
"name": "release",
"arkOptions": {
"obfuscation": {
"ruleOptions": {
"enable": true,
"files": [
"obfuscation-rules.txt"
]
}
}
}
}
]
}
}
# obfuscation-rules.txt
# 开启混淆
-enable-property-obfuscation
-enable-toplevel-obfuscation
-enable-filename-obfuscation
# 保留入口类
-keep
class * extends @ohos.ability.UIAbility
-keep
class * extends @ohos.ability.ExtensionAbility
# 保留ArkUI组件
-keep
class * extends @ohos.arkui.component.Component
import cryptoFramework from '@ohos.security.cryptoFramework';
class CryptoService {
// AES 加密
async aesEncrypt(plainText: string, key: string): Promise<string> {
const keyGenerator = cryptoFramework.createSymKeyGenerator('AES128');
const keyData = new Uint8Array(16);
for (let i = 0; i < 16; i++) {
keyData[i] = key.charCodeAt(i % key.length);
}
const symKey = await keyGenerator.convertKey({ data: keyData });
const cipher = cryptoFramework.createCipher('AES128|ECB|PKCS5');
await cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, symKey, null);
const input = { data: new Uint8Array(Buffer.from(plainText)) };
const output = await cipher.doFinal(input);
return Buffer.from(output.data).toString('base64');
}
// AES 解密
async aesDecrypt(cipherText: string, key: string): Promise<string> {
const keyGenerator = cryptoFramework.createSymKeyGenerator('AES128');
const keyData = new Uint8Array(16);
for (let i = 0; i < 16; i++) {
keyData[i] = key.charCodeAt(i % key.length);
}
const symKey = await keyGenerator.convertKey({ data: keyData });
const cipher = cryptoFramework.createCipher('AES128|ECB|PKCS5');
await cipher.init(cryptoFramework.CryptoMode.DECRYPT_MODE, symKey, null);
const input = { data: new Uint8Array(Buffer.from(cipherText, 'base64')) };
const output = await cipher.doFinal(input);
return Buffer.from(output.data).toString('utf-8');
}
// RSA 加密
async rsaEncrypt(plainText: string, publicKey: string): Promise<string> {
const keyGenerator = cryptoFramework.createAsyKeyGenerator('RSA1024');
const keyPair = await keyGenerator.convertKey(publicKey, null);
const cipher = cryptoFramework.createCipher('RSA1024|PKCS1');
await cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, keyPair.pubKey, null);
const input = { data: new Uint8Array(Buffer.from(plainText)) };
const output = await cipher.doFinal(input);
return Buffer.from(output.data).toString('base64');
}
// 哈希计算
async sha256(message: string): Promise<string> {
const md = cryptoFramework.createMd('SHA256');
await md.update({ data: new Uint8Array(Buffer.from(message)) });
const digest = await md.digest();
return Buffer.from(digest.data).toString('hex');
}
}
import prefs from '@ohos.data.preferences';
import crypto from '@ohos.security.cryptoFramework';
class SecureStorage {
private prefs: prefs.Preferences;
private cryptoService: CryptoService;
constructor(context: Context) {
this.prefs = prefs.getPreferences(context, 'secure_prefs');
this.cryptoService = new CryptoService();
}
// 安全存储
async securePut(key: string, value: string, encryptionKey: string): Promise<void> {
const encrypted = await this.cryptoService.aesEncrypt(value, encryptionKey);
await this.prefs.put(key, encrypted);
await this.prefs.flush();
}
// 安全读取
async secureGet(key: string, encryptionKey: string): Promise<string> {
const encrypted = await this.prefs.get(key, '') as string;
if (!encrypted) return '';
return await this.cryptoService.aesDecrypt(encrypted, encryptionKey);
}
}
// 证书锁定
class SecureHttpClient {
private context: Context;
constructor(context: Context) {
this.context = context;
}
async request(url: string, options: http.HttpRequestOptions): Promise<http.HttpResponse> {
const httpRequest = http.createHttp();
// 设置证书锁定
options.caPath = '/etc/ssl/certs/ca-certificates.crt';
// 设置请求超时
options.connectTimeout = 30000;
options.readTimeout = 30000;
// 设置安全头部
options.header = {
...options.header,
'X-Content-Type-Options': 'nosniff',
'X-Frame-Options': 'DENY',
'Strict-Transport-Security': 'max-age=31536000; includeSubDomains'
};
const response = await httpRequest.request(url, options);
httpRequest.destroy();
return response;
}
}
import abilityAccessCtrl from '@ohos.abilityAccessCtrl';
class PermissionManager {
// 检查权限
async checkPermission(context: Context, permission: string): Promise<boolean> {
const atManager = abilityAccessCtrl.createAtManager();
const grantStatus = await atManager.checkAccessToken(
context.applicationInfo.accessTokenId,
permission
);
return grantStatus === abilityAccessCtrl.GrantStatus.PERMISSION_GRANTED;
}
// 申请权限
async requestPermission(context: Context, permission: string): Promise<boolean> {
const atManager = abilityAccessCtrl.createAtManager();
const result = await atManager.requestPermissionsFromUser(context, [permission]);
return result.authResults[0] === 0;
}
// 申请多个权限
async requestPermissions(context: Context, permissions: string[]): Promise<boolean[]> {
const atManager = abilityAccessCtrl.createAtManager();
const result = await atManager.requestPermissionsFromUser(context, permissions);
return result.authResults.map(status => status === 0);
}
}
面试官视角: 考察候选人对移动应用安全的理解和实践经验,能否构建安全可靠的应用。
鸿蒙的分布式能力是其核心优势,主要体现在以下几个方面:
import deviceManager from '@ohos.distributedDeviceManager';
class DistributedDeviceService {
private dmInstance: deviceManager.DeviceManager;
constructor(context: Context) {
this.dmInstance = deviceManager.createDeviceManager(context.bundleName);
}
// 获取可信设备列表
getTrustedDevices(): Array<deviceManager.DeviceInfo> {
return this.dmInstance.getTrustedDeviceListSync();
}
// 监听设备状态变化
onDeviceStateChange(callback: (deviceInfo: deviceManager.DeviceInfo) => void): void {
this.dmInstance.on('deviceStateChange', (result) => {
switch (result.action) {
case deviceManager.DeviceStateChangeAction.ONLINE:
console.log(`设备上线: ${result.device.deviceName}`);
break;
case deviceManager.DeviceStateChangeAction.OFFLINE:
console.log(`设备下线: ${result.device.deviceName}`);
break;
case deviceManager.DeviceStateChangeAction.INFO_UPDATE:
console.log(`设备信息更新: ${result.device.deviceName}`);
break;
}
callback(result.device);
});
}
// 停止监听
offDeviceStateChange(): void {
this.dmInstance.off('deviceStateChange');
}
}
import distributedData from '@ohos.data.distributedData';
class DistributedDataService {
private kvManager: distributedData.KVManager;
private kvStore: distributedData.KVStore;
constructor(context: Context) {
const config: distributedData.KVManagerConfig = {
bundleName: context.bundleName,
userInfo: {
userId: '0',
userType: distributedData.UserType.SAME_USER_ID
}
};
this.kvManager = distributedData.createKVManager(config);
}
// 创建KVStore
async createKVStore(storeId: string): Promise<void> {
const options: distributedData.Options = {
createIfMissing: true,
encrypt: false,
backup: false,
autoSync: true,
kvStoreType: distributedData.KVStoreType.DEVICE_COLLABORATION,
schema: undefined,
securityLevel: distributedData.SecurityLevel.S1
};
this.kvStore = await this.kvManager.getKVStore(storeId, options);
}
// 订阅数据变化
subscribeDataChange(): void {
this.kvStore.on('dataChange', distributedData.SubscribeType.SUBSCRIBE_TYPE_ALL, (data) => {
console.log(`数据变化: ${JSON.stringify(data)}`);
});
}
// 存储数据
async put(key: string, value: string | number | boolean | Uint8Array): Promise<void> {
await this.kvStore.put(key, value);
}
// 获取数据
async get(key: string): Promise<string | number | boolean | Uint8Array> {
return await this.kvStore.get(key);
}
// 同步数据到其他设备
async sync(deviceIds: string[]): Promise<void> {
await this.kvStore.sync(deviceIds, distributedData.SyncMode.PUSH_PULL);
}
}
import distributedMissionManager from '@ohos.distributedMissionManager';
class MissionService {
// 继续在其他设备上运行
async continueMission(srcDeviceId: string, dstDeviceId: string, missionId: number): Promise<void> {
try {
await distributedMissionManager.continueMission({
srcDeviceId: srcDeviceId,
dstDeviceId: dstDeviceId,
missionId: missionId,
wantParam: {}
});
console.log('任务迁移成功');
} catch (error) {
console.error(`任务迁移失败: ${JSON.stringify(error)}`);
}
}
// 获取其他设备上的任务列表
async getMissions(deviceId: string): Promise<Array<distributedMissionManager.MissionInfo>> {
try {
const missions = await distributedMissionManager.getMissions(deviceId);
return missions;
} catch (error) {
console.error(`获取任务列表失败: ${JSON.stringify(error)}`);
return [];
}
}
}
| 场景 | 描述 | 核心技术 |
|---|---|---|
| 多屏协同 | 手机、平板、PC间无缝协作 | 分布式软总线、分布式任务调度 |
| 智能家居 | 多设备联动、场景控制 | 分布式设备管理、分布式数据管理 |
| 车载互联 | 手机与车机互联 | 分布式软总线、分布式数据管理 |
| 分布式游戏 | 多设备协同游戏体验 | 分布式任务调度、分布式软总线 |
| 超级终端 | 多设备融合为"超级终端" | 全部分布式能力 |
XComponent 是鸿蒙提供的自定义渲染组件,允许开发者使用原生图形API进行渲染。
import nativeRender from '@ohos.nativeRender';
import { XComponentContext } from '@ohos.nativeRender';
@Entry
@Component
struct XComponentDemo {
private xComponentContext: XComponentContext | null = null;
build() {
Column() {
XComponent('xcomponent', {
id: 'xcomponent',
type: 'surface',
libraryname: 'native_render'
})
.onLoad((context: XComponentContext) => {
this.xComponentContext = context;
this.initRender();
})
.onDestroy(() => {
this.releaseRender();
})
.width('100%')
.height('50%')
}
.width('100%')
.height('100%')
}
private initRender(): void {
if (this.xComponentContext) {
this.xComponentContext.surfaceSizeChangeCallback = (width: number, height: number) => {
console.log(`Surface size changed: ${width}x${height}`);
};
}
}
private releaseRender(): void {
// 释放渲染资源
}
}
// native_render.cpp
#include <napi/native_api.h>
#include <EGL/egl.h>
#include <GLES3/gl3.h>
// EGL 显示和上下文
static EGLDisplay eglDisplay = EGL_NO_DISPLAY;
static EGLContext eglContext = EGL_NO_CONTEXT;
static EGLSurface eglSurface = EGL_NO_SURFACE;
// 初始化 EGL
static napi_value InitEGL(napi_env env, napi_callback_info info) {
// 获取默认显示
eglDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY);
if (eglDisplay == EGL_NO_DISPLAY) {
return nullptr;
}
// 初始化 EGL
EGLint major, minor;
if (!eglInitialize(eglDisplay, &major, &minor)) {
return nullptr;
}
// 配置 EGL
EGLint configAttribs[] = {
EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
EGL_RED_SIZE, 8,
EGL_GREEN_SIZE, 8,
EGL_BLUE_SIZE, 8,
EGL_ALPHA_SIZE, 8,
EGL_DEPTH_SIZE, 24,
EGL_NONE
};
EGLConfig config;
EGLint numConfigs;
if (!eglChooseConfig(eglDisplay, configAttribs, &config, 1, &numConfigs)) {
return nullptr;
}
// 创建上下文
EGLint contextAttribs[] = {
EGL_CONTEXT_CLIENT_VERSION, 3,
EGL_NONE
};
eglContext = eglCreateContext(eglDisplay, config, EGL_NO_CONTEXT, contextAttribs);
return nullptr;
}
// 渲染帧
static napi_value RenderFrame(napi_env env, napi_callback_info info) {
if (eglDisplay == EGL_NO_DISPLAY || eglSurface == EGL_NO_SURFACE) {
return nullptr;
}
// 清屏
glClearColor(0.2f, 0.3f, 0.3f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
// 交换缓冲区
eglSwapBuffers(eglDisplay, eglSurface);
return nullptr;
}
鸿蒙 NDK(Native Development Kit)允许开发者使用 C/C++ 开发高性能模块。
my_ndk_project/
├── entry/
│ ├── src/
│ │ └── main/
│ │ ├── cpp/
│ │ │ ├── CMakeLists.txt
│ │ │ ├── native_hello.cpp
│ │ │ └── types/
│ │ │ └── libhello.d.ts
│ │ ├── ets/
│ │ └── module.json5
│ └── build-profile.json5
└── oh-package.json5
```cpp
// native_hello.cpp
#include
#include
#define LOG_PRINT_DOMAIN 0x0001
#define LOG_TAG "NativeDemo"
// 导出函数
static napi_value Add