import { moduleInstallManager } from '@kit.StoreKit';import { hilog } from '@kit.PerformanceAnalysisKit';import { BusinessError, Callback } from '@kit.BasicServicesKit';import { common } from '@kit.AbilityKit';import { promptAction } from '@kit.ArkUI';
const TAG: string = 'TAG';
@Entry@Componentstruct Index {  @BuilderParam AModulelibComponent: Function;  @State countTotal: number = 0;  @State isShow: boolean = false;
  build() {    Row() {      Column() {        Button(`调用增量模块中的add功能:3+6`)          .onClick(() => {            this.initAModulelib(() => {              import('AModulelib').then((ns: ESObject) => {                this.countTotal = ns.add(3, 6);              }).catch((error: BusinessError) => {                hilog.error(0, 'TAG', `add onError.code is ${error.code}, message is ${error.message}`);              })            })          });        Text('计算结果:' + this.countTotal)          .margin(10);        Button(`调用增量模块中的showDateComponent功能`)          .onClick(() => {            this.initAModulelib(() => {              import('AModulelib').then((ns: ESObject) => {                this.AModulelibComponent = ns.showDateComponent;                this.isShow = true;              }).catch((error: BusinessError) => {                hilog.error(0, 'TAG', `showDateComponent onError.code is ${error.code}, message is ${error.message}`);              })            })          }).margin({          top: 10, bottom: 10        });        if (this.isShow) {          this.AModulelibComponent()        }      }      .width('100%')    }    .height('100%')  }
  private showToastInfo(msg: string) {    promptAction.showToast({      message: msg,      duration: 2000    });  }
  /**   * 检查是否已加载AModulelib包   *   * @param successCallBack 回调   */  private initAModulelib(successCallBack: Callback<void>): void {    try {      const result: moduleInstallManager.InstalledModule = moduleInstallManager.getInstalledModule('AModulelib');      if (result?.installStatus === moduleInstallManager.InstallStatus.INSTALLED) {        hilog.info(0, TAG, 'AModulelib installed');        successCallBack && successCallBack();      } else {        // AModulelib模块未安装, 需要调用fetchModules下载AModulelib模块。        hilog.info(0, TAG, 'AModulelib not installed');        this.fetchModule('AModulelib', successCallBack)      }    } catch (error) {      hilog.error(0, 'TAG', `getInstalledModule onError.code is ${error.code}, message is ${error.message}`);    }  }
  /**   * 添加监听事件   *   * @param successCallBack 回调   */  private onListenEvents(successCallBack: Callback<void>): void {    const timeout = 3 * 60; //单位秒, 默认最大监听时间为30min(即30*60秒)    moduleInstallManager.on('moduleInstallStatus', (data: moduleInstallManager.ModuleInstallSessionState) => {      // 返回成功      if (data.taskStatus === moduleInstallManager.TaskStatus.INSTALL_SUCCESSFUL) {        successCallBack && successCallBack();        this.showToastInfo('install success');      }    }, timeout)  }
  /**   * 加载指定包   *   * @param moduleName 需要加载的安装包名称   * @param successCallBack 回调   */  private fetchModule(moduleName: string, successCallBack: Callback<void>) {    try {      hilog.info(0, TAG, 'handleFetchModules start');      const context = getContext(this) as common.UIAbilityContext;      const moduleInstallProvider: moduleInstallManager.ModuleInstallProvider =        new moduleInstallManager.ModuleInstallProvider();      const moduleInstallRequest: moduleInstallManager.ModuleInstallRequest =        moduleInstallProvider.createModuleInstallRequest(context);      if (!moduleInstallRequest) {        hilog.warn(0, TAG, 'moduleInstallRequest is empty');        return;      }      moduleInstallRequest.addModule(moduleName);      moduleInstallManager.fetchModules(moduleInstallRequest)        .then((data: moduleInstallManager.ModuleInstallSessionState) => {          hilog.info(0, TAG, 'Succeeded in fetching Modules result.');          if (data.code === moduleInstallManager.RequestErrorCode.SUCCESS) {            this.onListenEvents(successCallBack)          } else {            hilog.info(0, TAG, 'fetchModules failure');          }        })        .catch((error: BusinessError) => {          hilog.error(0, 'TAG', `fetchModules onError.code is ${error.code}, message is ${error.message}`);        })    } catch (error) {      hilog.error(0, 'TAG', `handleFetchModules onError.code is ${error.code}, message is ${error.message}`);    }  }}
评论