鸿蒙系统开发入门:代码示例与详解

214 阅读7分钟

一、开发环境与项目结构

1.1 开发环境快速搭建

DevEco Studio安装步骤

1. 访问华为开发者联盟官网下载最新版DevEco Studio
2. 安装时勾选"添加到PATH"选项,自动配置环境变量
3. 首次启动后登录华为账号,自动下载HarmonyOS SDK
4. 配置模拟器:创建Phone类型模拟器,推荐分配4GB内存

环境验证代码

// 在Index.ets中输入以下代码,验证环境是否正常
@Entry
@Component
struct HelloWorld {
  build() {
    Column() {
      Text("Hello HarmonyOS")
        .fontSize(30)
        .fontColor(Color.Blue)
    }
    .width("100%")
    .height("100%")
    .justifyContent(FlexAlign.Center)
  }
}

1.2 标准项目结构解析

核心目录说明

entry/src/main/ets/
├── entryability/       # 应用入口
│   └── EntryAbility.ts # 应用生命周期管理
├── pages/              # 页面目录
│   └── Index.ets       # 首页
├── components/         # 自定义组件
└── models/             # 数据模型

配置文件解析

// module.json5关键配置
{
  "module": {
    "name": "entry",
    "type": "entry",
    "abilities": [
      {
        "name": "EntryAbility",
        "srcEntry": "./ets/entryability/EntryAbility.ts",
        "launchType": "standard"
      }
    ]
  }
}

二、ArkTS核心语法示例

2.1 基础数据类型与变量声明

变量与常量声明

// 基础数据类型
let count: number = 10;          // 数字类型
let message: string = "Hello";   // 字符串类型
let isDone: boolean = false;     // 布尔类型

// 常量声明(不可修改)
const MAX_COUNT: number = 100;   // 数值常量
const APP_NAME: string = "MyApp";// 字符串常量

// 数组类型
let numbers: number[] = [1, 2, 3];
let fruits: Array<string> = ["apple", "banana"];

// 对象类型
interface Person {
  name: string;
  age: number;
}
let user: Person = { name: "Tom", age: 20 };

类型推断特性

// TypeScript自动类型推断
let score = 95; // 自动推断为number类型
let name = "Alice"; // 自动推断为string类型

// 联合类型
let value: string | number;
value = "hello";  // 合法
value = 123;      // 合法

2.2 函数定义与调用

基础函数示例

// 基本函数定义
function add(a: number, b: number): number {
  return a + b;
}

// 箭头函数
const multiply = (a: number, b: number): number => a * b;

// 可选参数与默认值
function greet(name: string, title?: string = "Mr."): string {
  return `Hello, ${title}${name}`;
}

// 函数调用示例
let sum = add(3, 5);          // sum = 8
let product = multiply(4, 6); // product = 24
let message = greet("Smith");  // message = "Hello, Mr.Smith"

2.3 类与面向对象

类定义与使用

// 类定义
class Animal {
  private name: string;  // 私有属性
  
  constructor(name: string) {
    this.name = name;
  }
  
  // 公有方法
  public getName(): string {
    return this.name;
  }
  
  // 抽象方法(需要子类实现)
  public makeSound(): void {
    console.log(`${this.name} makes a sound`);
  }
}

// 类继承
class Dog extends Animal {
  constructor(name: string) {
    super(name);
  }
  
  // 重写父类方法
  public makeSound(): void {
    console.log(`${this.getName()} barks: Woof! Woof!`);
  }
  
  // 新增方法
  public fetch(): void {
    console.log(`${this.getName()} is fetching the ball`);
  }
}

// 使用示例
let dog = new Dog("Buddy");
dog.makeSound(); // 输出: Buddy barks: Woof! Woof!
dog.fetch();     // 输出: Buddy is fetching the ball

三、UI组件与布局实现

3.1 基础组件使用

常用UI组件示例

// 文本组件
Text("Hello HarmonyOS")
  .fontSize(24)          // 字体大小
  .fontColor(Color.Blue) // 字体颜色
  .fontWeight(FontWeight.Bold) // 字体粗细
  .margin(10)            // 外边距

// 按钮组件
Button("Click Me")
  .width(150)            // 宽度
  .height(40)            // 高度
  .backgroundColor(Color.Green) // 背景色
  .onClick(() => {      // 点击事件
    console.log("Button clicked");
  })

// 图片组件
Image($r("app.media.icon")) // 使用资源图片
  .width(100)
  .height(100)
  .objectFit(ImageFit.Cover) // 图片适配方式
  .borderRadius(10)        // 圆角

// 输入框组件
TextInput({ placeholder: "请输入文本" })
  .width("80%")
  .height(40)
  .backgroundColor(Color.White)
  .padding(10)            // 内边距
  .onChange((value) => {  // 内容变化事件
    console.log("输入内容: " + value);
  })

3.2 常用布局容器

布局容器示例

// 垂直布局
Column() {
  Text("Item 1")
  Text("Item 2")
  Text("Item 3")
}
.width("100%")
.padding(10)
.spacing(5) // 子组件间距
.justifyContent(FlexAlign.Center) // 垂直对齐方式

// 水平布局
Row() {
  Text("Left")
  Text("Center")
  Text("Right")
}
.width("100%")
.justifyContent(FlexAlign.SpaceBetween) // 水平对齐方式
.height(50)
.backgroundColor("#F5F5F5")

// 层叠布局
Stack() {
  Image($r("app.media.background"))
    .width("100%")
    .height(200)
  
  Text("Overlay Text")
    .fontSize(20)
    .fontColor(Color.White)
}
.width("100%")
.height(200)

// 列表布局
List({ space: 5 }) {
  ForEach([1, 2, 3], (item) => {
    ListItem() {
      Text(`List Item ${item}`)
        .width("100%")
        .padding(15)
        .backgroundColor(Color.White)
    }
  })
}
.width("100%")
.backgroundColor("#F5F5F5")
.padding(10)

四、状态管理详解

4.1 组件状态管理

基础状态管理

@Entry
@Component
struct CounterComponent {
  // 组件内部状态
  @State count: number = 0
  
  build() {
    Column() {
      Text(`Count: ${this.count}`)
        .fontSize(24)
        .margin(10)
      
      Button("Increment")
        .onClick(() => {
          // 修改状态变量,自动触发UI刷新
          this.count++
        })
        
      Button("Decrement")
        .onClick(() => {
          this.count--
        })
    }
    .width("100%")
    .height("100%")
    .justifyContent(FlexAlign.Center)
  }
}

4.2 父子组件通信

组件间数据传递

// 子组件
@Component
struct ChildComponent {
  // 接收父组件数据(单向传递)
  @Prop message: string
  
  // 子组件向父组件通信
  private onMessageChange: (newValue: string) => void
  
  build() {
    Column() {
      Text(`Child: ${this.message}`)
      
      Button("Change Message")
        .onClick(() => {
          let newValue = "Updated by child";
          this.onMessageChange(newValue);
        })
    }
  }
}

// 父组件
@Entry
@Component
struct ParentComponent {
  @State parentMessage: string = "Hello from parent"
  
  build() {
    Column() {
      Text(`Parent: ${this.parentMessage}`)
        .fontSize(18)
        .margin(10)
      
      // 父子组件通信
      ChildComponent({
        message: this.parentMessage,
        onMessageChange: (newValue) => {
          this.parentMessage = newValue;
        }
      })
    }
    .width("100%")
    .height("100%")
    .justifyContent(FlexAlign.Center)
  }
}

4.3 全局状态管理

应用级状态管理

// app.ets
import AppStorage from '@ohos.data.AppStorage';

// 初始化全局状态
AppStorage.SetOrCreate("theme", "light");
AppStorage.SetOrCreate("userName", "Guest");

// 组件中使用全局状态
@Component
struct ThemeSwitch {
  // 绑定全局状态
  @StorageProp("theme") currentTheme: string = "light"
  
  build() {
    Column() {
      Text(`Current Theme: ${this.currentTheme}`)
      
      Button("切换主题")
        .onClick(() => {
          // 修改全局状态
          AppStorage.SetOrCreate("theme", 
            this.currentTheme === "light" ? "dark" : "light");
        })
    }
  }
}

// 另一个组件中使用相同全局状态
@Component
struct UserInfo {
  @StorageProp("userName") userName: string = "Guest"
  
  build() {
    Text(`Welcome, ${this.userName}`)
  }
}

五、常见功能代码实现

5.1 页面路由与导航

页面跳转实现

// 导入路由模块
import router from '@ohos.router';

// 跳转到详情页
Button("Go to Detail")
  .onClick(() => {
    router.pushUrl({
      url: "pages/DetailPage", // 目标页面路径
      params: {               // 传递参数
        id: 123,
        title: "示例页面"
      }
    })
  })

// 详情页接收参数
// DetailPage.ets
import router from '@ohos.router';

@Entry
@Component
struct DetailPage {
  // 获取路由参数
  private params: any = router.getParams()
  
  build() {
    Column() {
      Text(`Detail Page - ID: ${this.params.id}`)
      Text(`Title: ${this.params.title}`)
      
      Button("返回")
        .onClick(() => {
          router.back(); // 返回上一页
        })
    }
  }
}

5.2 数据存储与读取

首选项存储

import preferences from '@ohos.data.preferences';

// 保存数据
async function saveData(key: string, value: string) {
  try {
    // 获取偏好设置实例
    let store = await preferences.getPreferences(globalThis.context, "app_prefs");
    
    // 保存数据
    await store.put(key, value);
    
    // 提交更改
    await store.flush();
    console.log(`Data saved: ${key}=${value}`);
  } catch (error) {
    console.error(`Save failed: ${error}`);
  }
}

// 读取数据
async function loadData(key: string): Promise<string | undefined> {
  try {
    let store = await preferences.getPreferences(globalThis.context, "app_prefs");
    return await store.get(key, "default_value");
  } catch (error) {
    console.error(`Load failed: ${error}`);
    return undefined;
  }
}

// 使用示例
saveData("username", "john_doe");
loadData("username").then(value => {
  console.log(`Loaded username: ${value}`);
});

5.3 网络请求

HTTP请求示例

import http from '@ohos.net.http';

// 发起GET请求
async function fetchData(url: string): Promise<any> {
  let request = http.createHttp();
  
  try {
    let response = await request.request(
      url,
      {
        method: http.RequestMethod.GET,
        header: {
          'Content-Type': 'application/json'
        },
        connectTimeout: 60000,
        readTimeout: 60000
      }
    );
    
    if (response.responseCode === 200) {
      return JSON.parse(response.result as string);
    } else {
      console.error(`Request failed with code: ${response.responseCode}`);
      return null;
    }
  } catch (error) {
    console.error(`Request error: ${error}`);
    return null;
  } finally {
    // 销毁请求对象
    request.destroy();
  }
}

// 使用示例
fetchData("https://api.example.com/data")
  .then(data => {
    if (data) {
      console.log("Fetched data:", data);
    }
  });

六、代码规范与最佳实践

6.1 命名规范

代码命名示例

// 类名:大驼峰命名法
class UserProfile {
  // 私有属性:小驼峰,前缀下划线
  private _userName: string;
  
  // 公有属性:小驼峰
  public userId: number;
  
  // 常量:全大写,下划线分隔
  public static MAX_RETRY_COUNT: number = 3;
  
  // 方法名:小驼峰,动词开头
  public getUserInfo(): UserInfo {
    // 局部变量:小驼峰
    let userData: UserData = this.fetchUserData();
    return this.formatUserData(userData);
  }
  
  // 布尔类型方法:is/has开头
  public isUserLoggedIn(): boolean {
    return this._userName !== undefined;
  }
}

6.2 性能优化技巧

代码优化示例

// 优化前:循环中重复获取属性
for (let i = 0; i < list.length; i++) {
  // 每次循环都获取list.length
  console.log(list[i]);
}

// 优化后:缓存属性值
const length = list.length;
for (let i = 0; i < length; i++) {
  console.log(list[i]);
}

// 优化前:频繁创建对象
function processData(dataArray: any[]) {
  dataArray.forEach(item => {
    // 每次迭代创建新对象
    const processor = new DataProcessor();
    processor.process(item);
  });
}

// 优化后:复用对象
function processData(dataArray: any[]) {
  const processor = new DataProcessor(); // 创建一次
  dataArray.forEach(item => {
    processor.process(item); // 复用对象
  });
}

// 列表优化:使用LazyForEach实现懒加载
List() {
  LazyForEach(this.dataSource, (item) => {
    ListItem() {
      ItemComponent({ item: item })
    }
  })
}

七、常见错误与调试技巧

7.1 常见错误及解决方案

典型错误示例

// 错误1:状态更新不触发UI刷新
// 问题:直接修改数组元素
this.items[0] = "new value"; // 不会触发刷新

// 解决方案:创建新数组
this.items = this.items.map((item, index) => 
  index === 0 ? "new value" : item
);

// 错误2:布局嵌套过深
// 问题:过度嵌套导致性能问题
Column() {
  Row() {
    Column() {
      Row() {
        // 过深嵌套
      }
    }
  }
}

// 解决方案:扁平化布局,使用Flex
Flex({ direction: FlexDirection.Column }) {
  Flex({ justifyContent: FlexAlign.SpaceBetween }) {
    // 简化布局层级
  }
}

// 错误3:未处理异步操作
// 问题:在异步操作外使用结果
let data;
fetchData().then(result => {
  data = result;
});
console.log(data); // 此处data为undefined

// 解决方案:正确处理异步
fetchData().then(result => {
  console.log(result); // 在回调中使用结果
});

// 或使用async/await
async function process() {
  let data = await fetchData();
  console.log(data);
}

7.2 调试工具使用

调试技巧示例

// 日志输出
console.log("常规日志信息");
console.info("提示性信息");
console.warn("警告信息");
console.error("错误信息");

// 条件断点
if (someCondition) {
  // 在这行设置断点,右键设置条件
  console.log("满足条件时执行");
}

// 使用Profiler分析性能
// 在DevEco Studio中打开Profiler工具
// 记录并分析CPU和内存使用情况

// 远程调试
// 1. 连接设备并启用USB调试
// 2. 在DevEco Studio中选择设备
// 3. 使用"Debug"模式运行应用

八、进阶学习资源推荐

8.1 官方代码示例库

推荐示例项目

8.2 进阶学习路径

推荐学习资源

  1. 鸿蒙开发燾啊的动态 - 哔哩哔哩

结语:代码实践与提升

本教程通过丰富的代码示例和详细讲解,介绍了鸿蒙开发的核心语法和常用功能实现。要真正掌握鸿蒙开发,关键在于多动手实践:

  1. 从简单组件开始:先实现基础UI组件和布局
  2. 逐步构建完整应用:从单页面到多页面应用
  3. 参与开源项目:通过贡献代码提升实战能力
  4. 阅读优秀代码:学习开源项目的代码规范和架构设计

记住,编程学习最有效的方法是"边学边练",每个知识点都要通过实际代码验证和拓展。随着鸿蒙生态的不断发展,持续学习和实践将帮助你成为一名优秀的鸿蒙开发者。