HarmonyOS NEXT-鸿蒙开发多module学习

389 阅读1分钟

鸿蒙开发多module学习

简介

  • 一个应用通常会包含多种功能,将不同的功能特性按模块来划分和管理是一种良好的设计方式。在开发过程中,我们可以将每个功能模块作为一个独立的Module进行开发,Module中可以包含源代码、资源文件、第三方库、配置文件等,每一个Module可以独立编译,实现特定的功能。这种模块化、松耦合的应用管理方式有助于应用的开发、维护与扩展。

如何多使用多个module

  1. 在项目目录顶层(项目名)邮件创建Module,并设置Module名称
  2. 在新模块中正常编写UI
  3. 模拟器运行时记得选择主入口模块,避免被默认运行新模块

choseEntry.png

在主模块中拉起新模块

AppDataPersistence/entry/src/main/ets/pages/Index.ets

import { common, Want } from '@kit.AbilityKit';

@Entry
@Component
struct Index {
   message: string = '数据持久化';
  // 拉起其他 module 或者 ability时 需要上下文对象
  context: common.UIAbilityContext = getContext(this) as common.UIAbilityContext
  build() {
    Column({ space: 30 }) {
      Text(this.message).fontSize(26)

      Button("preferences")
        .onClick(() => {
          let wantInfo: Want = {
            deviceId: '', // 本设备
            // bundleName: 'com.dxin.appdatapersistence', //应用包名
            bundleName:getContext(this.context).applicationInfo.name, //也可动态获取
            moduleName: 'preferences', // 目标 模块名称
            abilityName: 'PreferencesAbility', // 该模块下可能有多个 ability
            parameters: {
              info: { name: "dxin-preferences"}// 参数可以省略
            }
          }
          this.context.startAbility(wantInfo)
        })
    }
    .width('100%')
    .height('100%')
    .backgroundColor($r('app.color.theme_color'))
  }
}

Want参数解释: deviceId: 设备ID,默认为空,即本设备。 bundleName: 本项目的bundleName,可以在AppScope/app.json5中查看 也可以通过getContext(this.context).applicationInfo.name动态获取 moduleName: 被拉起的模块名,在被拉起的模块module.json5中查看。 abilityName:被拉起模块的入口Ability名程,在被拉起的模块module.json5中查看。 parameters: 主模块可传参到被拉起的模块中。

在新模块入口类中获取参数并使用

入口类中获取参数并全局存储,方便UI获取。获取参数时如果是对象类型,还需要自行定义数据结构以适配接收。

AppDataPersistence/preferences/src/main/ets/preferencesability/PreferencesAbility.ets

import { AbilityConstant, UIAbility, Want } from '@kit.AbilityKit';
import { window } from '@kit.ArkUI';

export default class PreferencesAbility extends UIAbility {
  onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void {
    console.log("dxin => PreferencesAbility is Created")
    // 获取主模块传递过来的参数
    let abilityWant = want
    let info = abilityWant?.parameters?.info || '首选项'
    AppStorage.setOrCreate("info",info)
  }

  onWindowStageCreate(windowStage: window.WindowStage): void {
    windowStage.loadContent('pages/Index', (err) => {
      if (err.code) {
        return;
      }
    });
  }
 // ...
}

UI中进行获取并渲染

AppDataPersistence/preferences/src/main/ets/pages/Index.ets

@Entry
@Component
struct Index {
  @State moduleName: string = '首选项Preferences';
  @StorageProp("info") message:string = ""
  build() {
    Column({ space: 30 }) {
      Text(this.moduleName).fontSize(26)
      Text("主模块拉起时传递的参数:" + this.message).fontColor("#fff50909")
    }
    .width('100%')
    .height('100%')
    .backgroundColor($r('app.color.theme_color'))
  }
}