← 返回首页← 专题总览

鸿蒙 HarmonyOS 开发指南

- [第一部分:基础入门](#第一部分入门)
前端架构师通关手册 · 专题 23

目录


第一部分:基础入门

1. 鸿蒙系统概述

1.1 什么是 HarmonyOS

HarmonyOS(鸿蒙)是华为面向全场景智慧化时代,自主研发的一款全新的分布式操作系统。它基于微内核架构设计,采用分布式技术,能够实现跨终端无缝协同体验,为不同设备的智能化、互联与协同提供了统一的操作系统。

核心理念:

1.2 鸿蒙与安卓的主要区别

对比维度HarmonyOSAndroid
内核架构微内核(LiteOS/AliOS)宏内核(Linux)
分布式能力原生支持,系统级需要第三方SDK或厂商定制
开发语言ArkTS、C/C++、JavaJava/Kotlin
应用包格式.app / .hap.apk/.aab
性能特点轻量、低时延、高安全生态成熟,资源丰富
适用场景全场景IoT、智能终端以手机为主

1.3 鸿蒙系统架构

HarmonyOS 采用分层架构设计,从上到下依次为:

┌─────────────────────────────────────────────┐
│              应用层(Application)            │
├─────────────────────────────────────────────┤
│          框架层(Framework)                   │
│         - ArkUI 开发框架                      │
│         - Ability 框架                        │
│         - 分布式能力                          │
├─────────────────────────────────────────────┤
│          服务层(System Service)              │
│         - 分布式软总线                        │
│         - 分布式数据管理                      │
│         - 分布式任务调度                      │
├─────────────────────────────────────────────┤
│          内核层(Kernel)                      │
│         - Linux 内核                         │
│         - LiteOS 内核                        │
│         - 鸿蒙微内核                          │
└─────────────────────────────────────────────┘
关键特性:

2. 开发环境准备

2.1 安装 DevEco Studio

DevEco Studio 是华为提供的鸿蒙应用开发官方IDE,基于 IntelliJ IDEA 社区版开发。

安装步骤:
  1. 访
问 [华为开发者联盟](https://developer.huawei.com/consumer/cn/deveco-studio/) 下载安装包
  1. 安
装 JDK(推荐使用内置的JDK或OpenJDK 1.8+)
  1. 运
行安装程序,选择安装路径
  1. 启
动 DevEco Studio,登录华为开发者账号 系统要求:

2.2 配置 SDK

DevEco Studio 内置 SDK Manager,可以下载不同版本的鸿蒙 SDK:

  1. 打
开 DevEco Studio,进入 Settings → SDK Manager
  1. 选
择 HarmonyOS SDK 标签页
  1. 勾
选需要的 SDK 组件: 4. 点击 Apply 下载并安装

2.3 创建第一个项目

  1. 点
击 Create Project
  1. 选
择 Application → Empty Ability 模板
  1. 配
置项目信息: 4. 点击 Finish,等待项目初始化

3. 核心概念

3.1 Ability 框架

Ability 是鸿蒙应用的基本组成单元,分为两种类型:

Feature Ability (FA)

Particle Ability (PA)

Stage 模型下的 Ability:

3.2 页面路由

鸿蒙应用采用页面栈管理机制:

import router from '@ohos.router';

// 跳转到新页面
router.pushUrl({
  url: 'pages/Index',
  params: { id: 123 }
});

// 替换当前页面
router.replaceUrl({
  url: 'pages/Detail'
});

// 返回上一页
router.back();

3.3 ArkTS 语言基础

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
}

3.4 ArkUI 组件基础

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)
  }
}

4. 状态管理

4.1 状态装饰器

鸿蒙提供了多种状态装饰器来管理数据:

装饰器说明使用场景
@State组件内部状态,变化触发UI刷新页面内状态管理
@Prop父组件向子组件单向传递父子组件通信
@Link父组件与子组件双向绑定需要双向同步的场景
@Provide/@Consume祖先与后代组件跨层级传递跨层级状态共享
@Observed/@Object对象级别的响应式复杂对象状态监听
| @StorageLink/@LocalStorage | UI状态持久化,页面间共享 | 需要持久化的状态 | 示例:
// @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')
  }
}

4.2 AppStorage 和 LocalStorage

AppStorage:应用全局的状态管理,跨Ability共享
// 在 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)}`)
  }
}

5. 网络编程

5.1 HTTP 请求

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');

5.2 WebSocket 通信

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();
  }
}

6. 数据存储

6.1 Preferences (键值对存储)

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();
  }
}

6.2 关系型数据库 (RDB)

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);
  }
}

第二部分:进阶开发

7. 自定义组件

7.1 组件定义与复用

// 自定义按钮组件
@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)
  }
}

7.2 组件生命周期

@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)
  }
}

8. 动画与交互

8.1 属性动画

@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)
  }
}

8.2 转场动画

@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)
  }
}

8.3 手势处理

@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)
  }
}

9. 分布式能力

9.1 分布式设备管理

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');
  }
}

9.2 分布式数据管理

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);
  }
}

9.3 分布式任务调度

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 [];
    }
  }
}

10. 多媒体开发

10.1 音频播放

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();
  }
}

10.2 相机与视频

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();
  }
}

11. 安全与权限

11.1 权限申请

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'
);

11.2 数据加密

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');
  }
}

第三部分:资深进阶

12. 性能优化

12.1 渲染性能优化

// 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);
    });
  }
}

12.2 内存管理

// 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;
  }
}

12.3 启动优化

// 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;
}

13. 自定义渲染 (XComponent)

13.1 使用 XComponent 进行原生渲染

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 {
    // 释放渲染资源
  }
}

14. Native 开发 (C/C++)

14.1 NDK 开发基础

// 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);
}

14.2 ArkTS 与 Native 交互

// 导入 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)
  }
}

15. 测试与调试

15.1 单元测试

// 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;
}

15.2 UI 测试

// 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元素
    });
  });
}

16. 发布与部署

16.1 应用签名

  1. <
strong>生成密钥和证书请求文件 2. 进入 File → Project Structure → Signing Configs
  1. 勾
选 "Automatically generate signature"
  1. 系
统自动生成密钥和证书
  1. <
strong>手动签名配置

16.2 应用打包

  1. <
strong>HAP 包(Harmony Ability Package)
  1. <
strong>APP 包(Application Package) 打包步骤:
  1. 选
择 Build → Build Hap(s)/APP(s) → Build APP(s)
  1. 选
择目标设备类型和API版本
  1. 等
待构建完成
  1. 在
build 目录下找到生成的 .app 文件

第四部分:面试题与答案详解

一、基础篇

1. 请简述 HarmonyOS 的核心特性及其优势。

参考答案:

HarmonyOS 的核心特性包括:

  1. <
strong>分布式架构
  1. <
strong>微内核设计
  1. <
strong>弹性部署
  1. <
strong>确定性时延引擎
  1. <
strong>方舟编译器 面试官视角: 考察候选人对鸿蒙系统的整体认知,是否理解其设计哲学和与竞品的差异化优势。

2. 解释 Stage 模型与 FA 模型的区别。

参考答案:
对比维度FA 模型Stage 模型
应用组件Feature Ability + Particle AbilityUIAbility + ExtensionAbility
生命周期页面级生命周期Ability级生命周期
上下文PageAbilityContextUIAbilityContext
窗口管理无独立窗口概念支持多窗口和场景化
分布式能力基础支持增强支持
推荐使用已停止更新官方推荐
关键区别:
  1. <
strong>组件模型
  1. <
strong>生命周期管理
  1. <
strong>窗口支持
  1. <
strong>上下文能力 面试官视角: 考察候选人对鸿蒙应用架构演进的理解,是否了解最新技术方向。

3. 鸿蒙应用的基本组成单元是什么?请详细说明。

参考答案:

鸿蒙应用的基本组成单元是 Ability,分为以下类型:

UIAbility

  Create → Foreground → Background → Destroy
  

ExtensionAbility

卡片(FormAbility)

面试官视角: 考察候选人对鸿蒙应用基本架构的掌握程度,是否理解不同组件的职责划分。

4. 请解释 ArkTS 与 TypeScript 的关系和区别。

参考答案:

ArkTS 是基于 TypeScript 扩展而来的编程语言,专门为鸿蒙应用开发设计。

关系: 主要区别:
对比维度TypeScriptArkTS
UI开发需要配合框架内置声明式UI
状态管理需要第三方库内置装饰器支持
运行时JavaScript 引擎方舟编译运行时
性能JavaScript 解释执行静态编译优化
并发模型单线程支持多线程
新增特性:
  1. <
strong>@Entry、@Component、@State 等装饰器
  1. <
strong>声明式UI组件
  1. <
strong>状态管理装饰器
  1. <
strong>页面路由和生命周期
  1. <
strong>并发任务支持 面试官视角: 考察候选人对鸿蒙开发语言的理解,是否清楚其与Web开发的异同。

5. 请描述鸿蒙应用的生命周期。

参考答案:

UIAbility 生命周期

Create → WindowStageCreate → Foreground → Background → WindowStageDestroy → Destroy
各状态说明:
  1. <
strong>Create 状态
  1. <
strong>WindowStageCreate 状态
  1. <
strong>Foreground 状态
  1. <
strong>Background 状态
  1. <
strong>WindowStageDestroy 状态
  1. <
strong>Destroy 状态 代码示例:
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销毁');
  }
}
面试官视角: 考察候选人对鸿蒙应用运行机制的掌握,能否正确处理各生命周期阶段的操作。

6. 鸿蒙中的状态管理方式有哪些?请详细说明。

参考答案:

鸿蒙提供了丰富的状态管理装饰器,满足不同场景的需求:

1. @State(组件内部状态)

@Entry
@Component
struct Counter {
  @State count: number = 0; // 组件内部状态

  build() {
    Column() {
      Text(`计数: ${this.count}`)
      Button('增加')
        .onClick(() => {
          this.count++; // 修改后自动刷新UI
        })
    }
  }
}
适用场景:组件内部状态管理,变化触发当前组件重新渲染。

2. @Prop(单向传递)

@Component
struct ChildComponent {
  @Prop message: string; // 从父组件接收,单向绑定

  build() {
    Text(this.message)
  }
}

@Entry
@Component
struct Parent {
  @State msg: string = 'Hello';

  build() {
    ChildComponent({ message: this.msg })
  }
}
适用场景:父组件向子组件传递数据,子组件不能修改。

3. @Link(双向绑定)

@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 }) // 传递双向绑定
    }
  }
}
适用场景:需要父子组件双向同步数据的场景。

4. @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')
  }
}
适用场景:跨多层级组件共享状态,避免逐层传递。

5. @Observed/@Object(对象级响应式)

@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}`)
    }
  }
}
适用场景:复杂对象的属性变化监听。

6. AppStorage 和 LocalStorage

// AppStorage - 应用全局状态
AppStorage.SetOrCreate('userToken', 'abc123');

@Entry
@Component
struct UserPage {
  @StorageLink('userToken') userToken: string = '';

  build() {
    Text(`Token: ${this.userToken}`)
  }
}
适用场景:页面间共享数据、持久化存储。 面试官视角: 考察候选人对状态管理的全面理解,能否根据场景选择合适的状态管理方式。

7. 鸿蒙中如何实现页面跳转和参数传递?

参考答案:

鸿蒙提供了两种主要的页面跳转方式:

1. router 方式(页面路由)

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}`)
    }
  }
}

2. Navigation 组件(声明式导航)

@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('详情')
  }
}
两种方式的对比:
对比维度routerNavigation
使用方式命令式声明式
页面栈管理手动管理自动管理
转场动画需要自定义内置支持
复杂导航较难支持天然支持
推荐使用简单场景复杂场景
面试官视角: 考察候选人对页面导航的掌握程度,能否处理不同场景的页面跳转需求。

8. 请解释鸿蒙的分布式软总线技术。

参考答案:

分布式软总线是HarmonyOS的核心技术之一,为设备之间的互联互通提供统一的通信基座。

核心概念

分布式软总线是"连接鸿蒙生态设备的基石",它将多种通信方式(如Wi-Fi、蓝牙、NFC等)统一封装,为上层应用提供透明的连接能力。

技术架构

┌─────────────────────────────────────────────┐
│              应用层(分布式能力)              │
├─────────────────────────────────────────────┤
│           分布式软总线(Foundation)           │
│    ┌─────────┬─────────┬─────────┐          │
│    │ 发现    │ 连接    │ 传输    │          │
│    │ 模块    │ 模块    │ 模块    │          │
│    └─────────┴─────────┴─────────┘          │
├─────────────────────────────────────────────┤
│           协议栈(Wi-Fi/BLE/NFC)             │
└─────────────────────────────────────────────┘

核心能力

  1. <
strong>设备发现
  1. <
strong>设备连接
  1. <
strong>数据传输
  1. <
strong>设备管理

应用场景

  1. <
strong>多屏协同
  1. <
strong>超级终端
  1. <
strong>分布式游戏
  1. <
strong>智能家居控制 面试官视角: 考察候选人对鸿蒙核心技术的理解深度,能否将技术概念与实际应用场景结合。

9. 鸿蒙应用如何进行网络请求?

参考答案:

鸿蒙提供了 @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"
      }
    ]
  }
}
面试官视角: 考察候选人对网络编程的掌握程度,能否处理实际的网络请求场景。

10. 鸿蒙应用如何进行本地数据存储?

参考答案:

鸿蒙提供了多种本地数据存储方式:

1. Preferences(键值对存储)

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();
  }
}

2. 关系型数据库(RDB)

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;
  }
}

3. 分布式KV存储

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跨设备同步自动同步、高可用数据量有限
面试官视角: 考察候选人对数据存储方案的全面了解,能否根据业务需求选择合适的方式。

二、进阶篇

11. 请描述鸿蒙的动画实现方式。

参考答案:

鸿蒙提供了多种动画实现机制:

1. 属性动画(animateTo)

@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)
  }
}

2. 转场动画

@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)
  }
}

动画性能优化建议

  1. <
strong>优先使用 transform 属性:transform 和 opacity 可以由GPU加速
  1. <
strong>避免频繁布局:left、top、width、等属性会触发布局
  1. <
strong>使用 will-change:提前告知浏览器哪些属性会变化
  1. <
strong>合理使用动画曲线:避免过度动画影响用户体验 面试官视角: 考察候选人对动画原理和实现方式的掌握,能否创建流畅的用户体验。

12. 请描述鸿蒙的手势处理机制。

参考答案:

鸿蒙提供了丰富的手势识别和处理能力:

1. 基础手势

@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)
  }
}

2. 拖拽手势

@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)
  }
}

3. 缩放手势

@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)
  }
}

4. 组合手势

@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)
  }
}
面试官视角: 考察候选人对移动端手势处理的理解,能否创建自然流畅的交互体验。

13. 鸿蒙应用的性能优化有哪些方法?

参考答案:

1. 渲染性能优化

// 避免在 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%')
  }
}

2. 内存管理

// 及时释放资源
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('内存管理示例')
  }
}

3. 启动优化

// 延迟加载非关键资源
@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)
      }
    }
  }
}

4. 网络优化

// 请求合并、缓存、重试机制
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');
  }
}
面试官视角: 考察候选人对性能优化的理解和实践经验,能否综合应用多种优化手段。

14. 请描述鸿蒙的并发编程模型。

参考答案:

鸿蒙提供了多种并发编程方式:

1. TaskPool(任务池)

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}`);

2. Worker(工作线程)

// 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;
  });
}

3. 并发编程最佳实践

  1. <
strong>合理选择并发方式
  1. <
strong>避免共享状态
  1. <
strong>错误处理
  1. <
strong>资源管理 面试官视角: 考察候选人对并发编程的理解,能否合理利用多核CPU提升应用性能。

15. 鸿蒙应用如何进行安全加固?

参考答案:

1. 代码混淆

// 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

2. 数据加密

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');
  }
}

3. 安全存储

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);
  }
}

4. 网络安全

// 证书锁定
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;
  }
}

5. 权限管理

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);
  }
}
面试官视角: 考察候选人对移动应用安全的理解和实践经验,能否构建安全可靠的应用。

三、资深篇

16. 请描述鸿蒙的分布式能力及其应用场景。

参考答案:

鸿蒙的分布式能力是其核心优势,主要体现在以下几个方面:

1. 分布式设备管理

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');
  }
}

2. 分布式数据管理

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);
  }
}

3. 分布式任务调度

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 [];
    }
  }
}

4. 分布式应用场景

场景描述核心技术
多屏协同手机、平板、PC间无缝协作分布式软总线、分布式任务调度
智能家居多设备联动、场景控制分布式设备管理、分布式数据管理
车载互联手机与车机互联分布式软总线、分布式数据管理
分布式游戏多设备协同游戏体验分布式任务调度、分布式软总线
超级终端多设备融合为"超级终端"全部分布式能力
面试官视角: 考察候选人对鸿蒙分布式能力的深入理解和实际应用能力。

17. 请描述鸿蒙的自定义渲染(XComponent)开发。

参考答案:

XComponent 是鸿蒙提供的自定义渲染组件,允许开发者使用原生图形API进行渲染。

1. 基本使用

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 {
    // 释放渲染资源
  }
}

2. Native 渲染开发

// 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;
}

3. 应用场景

  1. <
strong>游戏开发:使用OpenGL ES进行高性能图形渲染
  1. <
strong>视频播放:自定义视频渲染管线
  1. <
strong>AR/VR:增强现实和虚拟现实应用
  1. <
strong>图像处理:实时图像滤镜和处理
  1. <
strong>数据可视化:复杂的图表和可视化渲染 面试官视角: 考察候选人对原生图形开发的理解,能否进行高性能的图形渲染开发。

18. 请描述鸿蒙的 NDK 开发。

参考答案:

鸿蒙 NDK(Native Development Kit)允许开发者使用 C/C++ 开发高性能模块。

1. NDK 项目结构

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

2. Native 模块开发

```cpp

// native_hello.cpp

#include

#include

#define LOG_PRINT_DOMAIN 0x0001

#define LOG_TAG "NativeDemo"

// 导出函数

static napi_value Add