文章目录
- 1. 实战概述
- 2. 实现步骤
- 2.1 创建鸿蒙应用项目
- 2.2 修改Index.ets代码
- 2.3 创建SecondAbility
- 2.4 创建Second.ets
 
- 3. 测试效果
- 4. 实战总结
- 5. 拓展练习 - 启动文件管理器
- 5.1 创建鸿蒙应用项目
- 5.2 修改Index.ets代码
- 5.3 测试应用运行效果
 
1. 实战概述
- 本实战详细阐述了在 HarmonyOS 上开发应用的过程,包括创建项目、修改页面代码、创建 Ability 以及页面间的数据传递。首先,通过 DevEco Studio 创建名为 WantStartAbility的鸿蒙项目。接着,对Index.ets页面进行编码,实现点击按钮后通过Want对象显式启动SecondAbility并传递参数。然后,创建SecondAbility类,在其onCreate方法中接收参数并存储在全局变量中。最后,通过Second.ets页面组件展示从SecondAbility获取的数据。整个流程涵盖了从项目初始化到具体编码实践的完整开发周期。
2. 实现步骤
2.1 创建鸿蒙应用项目
-  创建鸿蒙应用项目 - WantStartAbility
  
-  单击【Finish】按钮,生成应用基本框架 
  
2.2 修改Index.ets代码
- 首页 - pages/Index.ets
  
import { common, Want } from '@kit.AbilityKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
import { BusinessError } from '@kit.BasicServicesKit';
const TAG: string = '[Page_Index]';
const DOMAIN_NUMBER: number = 0xFF00;
@Entry
@Component
struct Index {
  @State message: string = 'Index页面';
  private context = getContext(this) as common.UIAbilityContext;
  build() {
    Row() {
      Column() {
        Text(this.message)
          .fontSize(40)
          .fontWeight(FontWeight.Bold)
          .foregroundColor(Color.Yellow)
          .margin('10')
        // 添加按钮
        Button('跳转')
          .fontSize(40)
          .width(150)
          .height(70)
          .backgroundColor('#44dd22')
          .foregroundColor('#ffffff')
          .onClick(() => {
            // 创建显式 Want 对象
            let wantInfo: Want = {
              deviceId: '', // deviceId 为空表示本设备
              bundleName: 'net.huawei.wsa', // 目标应用的包名
              abilityName: 'SecondAbility', // 目标 Ability 的名称
              parameters: {
                id: '20240101',
                name: '陈燕文',
                gender: '女',
                age: 19,
                major: '软件技术专业',
                class: '2024软件1班',
                telephone: '15893451170'
              },
            };
            // context为调用方UIAbility的UIAbilityContext
            this.context.startAbility(wantInfo).then(() => {
              hilog.info(DOMAIN_NUMBER, TAG, 'startAbility success.');
            }).catch((error: BusinessError) => {
              hilog.error(DOMAIN_NUMBER, TAG, 'startAbility failed.');
            });
          });
      }
      .width('100%');
    }
    .height('100%')
    .backgroundColor('#00662F')
  }
}
- 代码说明:这段代码定义了一个名为 Second的页面组件,使用 HarmonyOS 的 ArkUI 框架。页面包含一个文本显示和一个按钮,点击按钮后,通过Want对象显式启动名为SecondAbility的 Ability,并传递一系列参数。页面背景为深绿色(#00662F),文本为黄色加粗。启动 Ability 后,通过日志记录操作结果。
2.3 创建SecondAbility
- 在src/main/ets里创建SecondAbility
  
- 单击【Finish】按钮
  
- 创建完成之后,会自动在module.json5文件中注册该Ability
  
- 修改代码,将pages/Index改成pages/Second,接收传递来的参数,并写入全局变量
  
import { AbilityConstant, UIAbility, Want } from '@kit.AbilityKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
import { window } from '@kit.ArkUI';
// 定义Student接口
interface Student {
  id: string,
  name: string,
  gender: string,
  age: number,
  major: string,
  class: string,
  telephone: string
}
export default class SecondAbility extends UIAbility {
  // 定义Student对象
  static student: Student = {id: '', name: '', gender: '', age: 0, major: '', class: '', telephone: ''};
  onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void {
    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onCreate');
    // 接收调用方UIAbility传过来的参数
    let secondAbilityWant = want;
    SecondAbility.student.id = secondAbilityWant?.parameters?.id as string;
    SecondAbility.student.name = secondAbilityWant?.parameters?.name as string;
    SecondAbility.student.gender = secondAbilityWant?.parameters?.gender as string;
    SecondAbility.student.age = secondAbilityWant?.parameters?.age as number;
    SecondAbility.student.major = secondAbilityWant?.parameters?.major as string;
    SecondAbility.student.class = secondAbilityWant?.parameters?.class as string;
    SecondAbility.student.telephone = secondAbilityWant?.parameters?.telephone as string;
  }
  onDestroy(): void {
    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onDestroy');
  }
  onWindowStageCreate(windowStage: window.WindowStage): void {
    // Main window is created, set main page for this ability
    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onWindowStageCreate');
    windowStage.loadContent('pages/Second', (err) => {
      if (err.code) {
        hilog.error(0x0000, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err) ?? '');
        return;
      }
      hilog.info(0x0000, 'testTag', 'Succeeded in loading the content.');
    });
  }
  onWindowStageDestroy(): void {
    // Main window is destroyed, release UI related resources
    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onWindowStageDestroy');
  }
  onForeground(): void {
    // Ability has brought to foreground
    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onForeground');
  }
  onBackground(): void {
    // Ability has back to background
    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onBackground');
  }
}
- 代码说明:这段代码定义了 SecondAbility类,继承自UIAbility,用于管理应用的窗口和生命周期。在onCreate方法中,它接收启动参数并存储在静态student对象中。代码还包含了日志记录和页面加载逻辑,确保在窗口阶段创建时加载pages/Second页面。此外,定义了一个Student接口来描述接收的学生信息结构。
2.4 创建Second.ets
- 在pages里创建Second.ets文件
  
import SecondAbility from '../secondability/SecondAbility';
@Entry
@Component
struct Second {
  @State message: string = 'Second页面';
  @State student: string = '';
  build() {
    Row() {
      Column() {
        Text(this.message)
          .fontSize(40)
          .fontWeight(FontWeight.Bold)
          .foregroundColor(Color.Yellow)
          .margin('10')
        Text(this.student)
          .fontSize(30)
          .fontWeight(FontWeight.Bold)
          .foregroundColor(Color.Green)
          .margin('10')
        Button('接收')
          .fontSize(40)
          .width(150)
          .height(70)
          .backgroundColor('#44dd22')
          .foregroundColor('#ffffff')
          .onClick(() => {
            // 获取来自SecondAbility的数据
            let student: string = '学号:' + SecondAbility.student.id + '\n'
              + '姓名:' + SecondAbility.student.name + '\n'
              + '性别:' + SecondAbility.student.gender + '\n'
              + '年龄:' + SecondAbility.student.age + '\n'
              + '专业:' + SecondAbility.student.major + '\n'
              + '班级:' + SecondAbility.student.class + '\n'
              + '手机:' + SecondAbility.student.telephone;
            // 修改文本组件的内容
            this.student = student;
          })
      }
      .width('100%')
    }
    .height('100%')
    .backgroundColor('#00008B')
  }
}
- 代码说明:这段代码创建了一个 Second页面组件,其中包含两个文本区域和一个按钮。初始状态下,显示默认文本“Second页面”。点击“接收”按钮后,从SecondAbility中获取学生信息,并更新student状态以在页面上显示这些详细信息。页面背景为深蓝色(#00008B),默认文本为黄色加粗,学生信息文本为绿色加粗。此代码实现了 Ability 层与 UI 层间的数据交互和展示。
3. 测试效果
- 启动应用,显示首页
  
- 单击【跳转】按钮,显示第二个页面
  
- 单击【接收】按钮,显示接收的数据
  
4. 实战总结
- 通过本实战,我们掌握了在HarmonyOS中创建应用、实现页面跳转和数据传递的完整流程。首先,我们学习了如何使用DevEco Studio搭建项目框架。接着,通过编码实践,我们实现了从Index页面到SecondAbility的显式跳转,并传递了参数。在SecondAbility中,我们接收并处理了这些参数,随后在Second页面中展示了这些数据。此过程不仅加深了对HarmonyOS应用开发的理解,也提升了我们的实际开发技能。
5. 拓展练习 - 启动文件管理器
5.1 创建鸿蒙应用项目
-  创建鸿蒙应用项目 - StartFileManager
  
-  单击【Finish】按钮,生成应用基本框架 
  
5.2 修改Index.ets代码
- 首页 - pages/Index.ets
  
import { Want, common } from '@kit.AbilityKit';
function startFileManagement(context: common.UIAbilityContext): void {
  let want: Want = {
    bundleName: 'com.huawei.hmos.filemanager',
    abilityName: 'MainAbility'
  };
  context.startAbility(want);
}
@Entry
@Component
struct Index {
  @State message: string = 'Index页面';
  build() {
    Row() {
      Column() {
        Text(this.message)
          .fontSize(40)
          .fontWeight(FontWeight.Bold)
          .foregroundColor(Color.Yellow)
          .margin('10')
        // 添加按钮
        Button('文件管理器')
          .fontSize(30)
          .width(250)
          .height(70)
          .backgroundColor('#44dd22')
          .foregroundColor('#ffffff')
          .onClick(() => {
            const context: common.UIAbilityContext = getContext(this) as common.UIAbilityContext;
            startFileManagement(context);
          });
      }
      .width('100%');
    }
    .height('100%')
    .backgroundColor('#00662F')
  }
}
- 代码说明:这段代码基于鸿蒙开发框架编写。定义了startFileManagement函数用于构造Want对象并启动文件管理器应用。Index组件构建了页面布局,含显示文本与按钮,点击按钮时获取上下文来调用启动函数,旨在实现点击按钮启动文件管理器的交互操作。
5.3 测试应用运行效果
- 启动应用,显示首页
  
- 单击【文件管理器】按钮
  



















