目录

moduleInstallManager (On-Demand Feature Distribution)

This module allows you to separate specific functions and resources from the basic module of an app and include them in extended modules. Users can dynamically download the extended modules when using the app. On-demand feature distribution provides functions such as checking whether a module has been installed, requesting on-demand loading, listening for the download progress, displaying mobile data reminders, and canceling on-demand loading.

Exceptions need to be captured when an API is called.

Since: 4.1.0(11)

Modules to Import

import { moduleInstallManager } from '@kit.AppGalleryKit';

InstalledModule

Module installation information.

Model restriction: This API can be used only in the stage model.

System capability: SystemCapability.AppGalleryService.Distribution.OnDemandInstall

Since: 4.1.0(11)

Name Type Read-Only Optional Description
moduleName string Yes No Module name.
moduleType bundleManager.ModuleType Yes Yes

Module type.

Note: When the value of installStatus is 1, moduleType will return 0 by default, indicating an unknown type.

installStatus InstallStatus Yes No Module installation result.

ModuleInstallSessionState

Results of calling APIs for initiating requests, registering listeners, and unregistering listeners.

Model restriction: This API can be used only in the stage model.

System capability: SystemCapability.AppGalleryService.Distribution.OnDemandInstall

Since: 4.1.0(11)

Name Type Read-Only Optional Description
code RequestErrorCode Yes No API call result code.
taskStatus TaskStatus Yes No Status code of an on-demand download task.
taskId string Yes Yes ID of an on-demand download task. The default value is '0'.
desc string Yes No API call result description. The default value is "".
modules string[] Yes Yes List of module names in a download task. The default value is [].
totalSize number Yes Yes Total size of modules to be downloaded, in bytes. The default value is 0.
downloadedSize number Yes Yes Downloaded size, in bytes. The default value is 0.

InstallStatus

Enumerated status codes contained in the installation result.

Model restriction: This API can be used only in the stage model.

System capability: SystemCapability.AppGalleryService.Distribution.OnDemandInstall

Since: 4.1.0(11)

Name Value Description
INSTALLED 0 The specified module has been installed.
NOT_INSTALLED 1 The specified module has not been installed.

ReturnCode

Enumerated result codes of calling APIs for adding modules, canceling download, and displaying mobile data reminders.

Model restriction: This API can be used only in the stage model.

System capability: SystemCapability.AppGalleryService.Distribution.OnDemandInstall

Since: 4.1.0(11)

Name Value Description
SUCCESS 0 Successful.
FAILURE 1 Failed.

RequestErrorCode

Enumerated result codes of calling APIs for initiating requests, registering listeners, and unregistering listeners.

Model restriction: This API can be used only in the stage model.

System capability: SystemCapability.AppGalleryService.Distribution.OnDemandInstall

Since: 4.1.0(11)

Name Value Description
MODULE_DEBUG_FILES_SIZE_OVER_LIMIT -10

The total size of debug files of all modules in a single request exceeds 8 GB.

Since: 5.0.2(14)

MODULE_DEBUG_FILES_NOT_EXIST -9

The module debug file does not exist.

Since: 5.0.2(14)

MODULE_ALREADY_EXISTS -8 The module already exists.
MODULE_UNAVAILABLE -7 The module to be downloaded does not exist or does not match the device.
INVALID_REQUEST -6 The request is invalid because it contains inaccurate information.
NETWORK_ERROR -5 The request fails due to a network error.
INVOKER_VERIFICATION_FAILED -4 The caller information is abnormal.
FOREGROUND_REQUIRED -3 On-demand loading is allowed only when the app is running in the foreground.
ACTIVE_SESSION_LIMIT_EXCEEDED -2 The request is denied because at least one download task is in progress.
FAILURE -1 Failed.
SUCCESS 0 Successful.
DOWNLOAD_WAIT_WIFI 1 Mobile data is used. Call showCellularDataConfirmation to prompt users to confirm whether to use mobile data for download.

TaskStatus

Enumerated status codes of download tasks, returned by APIs for initiating requests, registering listeners, and unregistering listeners.

Model restriction: This API can be used only in the stage model.

System capability: SystemCapability.AppGalleryService.Distribution.OnDemandInstall

Since: 4.1.0(11)

Name Value Description
CREATE_TASK_FAILED -4 Failed to create a download task.
HIGHER_VERSION_INSTALLED -3 The same or a later version already exists on the user's device.
TASK_ALREADY_EXISTS -2 The download task already exists.
TASK_UNFOUND -1 No download task exists.
TASK_CREATED 0 A download task is created successfully.
DOWNLOADING 1 Downloading.
DOWNLOAD_PAUSING 2 Paused.
DOWNLOAD_WAITING 3 Pending download.
DOWNLOAD_SUCCESSFUL 4 Download completed.
DOWNLOAD_FAILED 5 Download failed.
DOWNLOAD_WAIT_WIFI 6 Scheduled to download with Wi-Fi.
INSTALL_WAITING 20 Waiting to install.
INSTALLING 21 Installing.
INSTALL_SUCCESSFUL 22 Installation completed.
INSTALL_FAILED 23 Installation failed.

moduleInstallManager.getInstalledModule

getInstalledModule(moduleName: string): InstalledModule

Queries module installation information.

Model restriction: This API can be used only in the stage model.

System capability: SystemCapability.AppGalleryService.Distribution.OnDemandInstall

Since: 4.1.0(11)

Parameters:

Parameter Type Mandatory Description
moduleName string Yes Name of the module to be obtained.

Returns:

Type Description
InstalledModule Module installation information.

Error codes:

For details about the error codes, please refer to ArkTS API Error Codes.

Error Code Error Message
401 Parameter error.
1006500001 Failed to invoke the BMS.

Example:

import { moduleInstallManager } from '@kit.AppGalleryKit';
import { hilog } from '@kit.PerformanceAnalysisKit';

@Entry
@Component
struct LoadInstallService {

  @State allInstalledModules: string = '';

  private getModuleInstanceInfo() {
    try {
      // Query module installation information.
      const result: moduleInstallManager.InstalledModule = moduleInstallManager.getInstalledModule('AModulelib');
      this.allInstalledModules = JSON.stringify(result);
      hilog.info(0, 'InstantDownload', 'getModuleInstanceInfo success=' + this.allInstalledModules);
    } catch (error) {
      hilog.error(0, 'InstantDownload', `getModuleInstanceInfo error.code is ${error.code}, message is ${error.message}`);
    }
  }

  build() {
    Column() {
    }
    .width('100%')
    .height('100%')
    .padding(16)
  }
}

InstallProvider

Parent class object of the controller in on-demand loading.

Model restriction: This API can be used only in the stage model.

System capability: SystemCapability.AppGalleryService.Distribution.OnDemandInstall

Since: 4.1.0(11)

InstallRequest

Parent class object of an on-demand loading request.

Model restriction: This API can be used only in the stage model.

System capability: SystemCapability.AppGalleryService.Distribution.OnDemandInstall

Since: 4.1.0(11)

ModuleInstallProvider

Implements on-demand loading and provides the capability of creating on-demand loading request objects. This method extends InstallProvider.

Model restriction: This API can be used only in the stage model.

System capability: SystemCapability.AppGalleryService.Distribution.OnDemandInstall

Since: 4.1.0(11)

[h2]ModuleInstallProvider.createModuleInstallRequest

createModuleInstallRequest(context: common.UIAbilityContext | common.ExtensionContext): ModuleInstallRequest

Creates an on-demand loading request object. You can set request parameters through the return value.

Model restriction: This API can be used only in the stage model.

System capability: SystemCapability.AppGalleryService.Distribution.OnDemandInstall

Since: 4.1.0(11)

Parameters:

Parameter Type Mandatory Description
context common.UIAbilityContext | common.ExtensionContext Yes Context of the app that calls the API.

Returns:

Type Description
ModuleInstallRequest On-demand download request object.

Error codes:

For details about the error codes, please refer to Universal Error Codes.

Error Code Error Message
401 Parameter error.

Example:

import { common } from '@kit.AbilityKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
import { moduleInstallManager } from '@kit.AppGalleryKit';

const TAG: string = 'createModuleInstallRequest';

@Entry
@Component
struct CreateModuleInstallRequest {

  build() {
    Column() {
      Button("createModuleInstallRequest")
        .onClick(() => {
          try {
            const myModuleInstallProvider: moduleInstallManager.ModuleInstallProvider =
              new moduleInstallManager.ModuleInstallProvider();
            const context: common.UIAbilityContext | common.ExtensionContext = this.getUIContext().getHostContext()  as common.UIAbilityContext;
            // Create an on-demand loading request object.
            const myModuleInstallRequest: moduleInstallManager.ModuleInstallRequest =
              myModuleInstallProvider.createModuleInstallRequest(context);
            hilog.info(0, TAG, `myModuleInstallRequest: ${JSON.stringify(myModuleInstallRequest)}`);
          } catch (error) {
            hilog.error(0, TAG, `createModuleInstallRequest onError.code is ${error.code}, message is ${error.message}`);
          }
        })
        .width('100%')
    }
    .margin(16)
    .height('100%')
    .justifyContent(FlexAlign.Center)
  }
}

ModuleInstallRequest

On-demand download request object, which extends InstallRequest.

Model restriction: This API can be used only in the stage model.

System capability: SystemCapability.AppGalleryService.Distribution.OnDemandInstall

Since: 4.1.0(11)

[h2]ModuleInstallRequest.addModule

addModule(moduleName: string): ReturnCode

Adds the name of the module to be loaded.

Model restriction: This API can be used only in the stage model.

System capability: SystemCapability.AppGalleryService.Distribution.OnDemandInstall

Since: 4.1.0(11)

Parameters:

Parameter Type Mandatory Description
moduleName string Yes Module name.

Returns:

Type Description
ReturnCode API call result code.

Error codes:

For details about the error codes, please refer to Universal Error Codes.

Error Code Error Message
401 Parameter error.

Example:

import { common } from '@kit.AbilityKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
import { moduleInstallManager } from '@kit.AppGalleryKit';

const TAG: string = 'addModule';

@Entry
@Component
struct AddModule {

  build() {
    Column() {
      Button("addModule")
        .onClick(() => {
          try {
            const myModuleInstallProvider: moduleInstallManager.ModuleInstallProvider =
              new moduleInstallManager.ModuleInstallProvider();
            const context: common.UIAbilityContext | common.ExtensionContext = this.getUIContext().getHostContext() as common.UIAbilityContext;
            // Create an on-demand loading request object.
            const myModuleInstallRequest: moduleInstallManager.ModuleInstallRequest =
              myModuleInstallProvider.createModuleInstallRequest(context);
            // Add the name of the module to be loaded.
            const aResult: moduleInstallManager.ReturnCode = myModuleInstallRequest.addModule('AModule');
            const bResult: moduleInstallManager.ReturnCode = myModuleInstallRequest.addModule('BModule');
            hilog.info(0, TAG, 'Succeeded in getting aResult:' + aResult + ' bResult:' + bResult);
          } catch (error) {
            hilog.error(0, TAG, `addModule onError.code is ${error.code}, message is ${error.message}`);
          }
        })
        .width('100%')
    }
    .margin(16)
    .height('100%')
    .justifyContent(FlexAlign.Center)
  }
}

moduleInstallManager.fetchModules

fetchModules(moduleInstallRequest: ModuleInstallRequest): Promise<ModuleInstallSessionState>

Requests on-demand loading and uses a promise to return the result. This API supports the debug mode.

Model restriction: This API can be used only in the stage model.

System capability: SystemCapability.AppGalleryService.Distribution.OnDemandInstall

Since: 4.1.0(11)

Parameters:

Parameter Type Mandatory Description
moduleInstallRequest ModuleInstallRequest Yes On-demand loading request object.

Returns:

Type Description
Promise<ModuleInstallSessionState> Promise used to return the results of calling the APIs for initiating requests, registering listeners, and unregistering listeners.

Error codes:

For details about the error codes, please refer to ArkTS API Error Codes.

Error Code Error Message
401 Parameter error.
1006500004 SA connection failed.
1006500008 Write param into container failed.
1006500009 Request to service error.
1006500010 Response from service cannot be recognized.

Example:

import { common } from '@kit.AbilityKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
import { moduleInstallManager } from '@kit.AppGalleryKit';

const TAG: string = 'fetchModules';

@Entry
@Component
struct FetchModules {

  build() {
    Column() {
      Button("fetchModules")
        .onClick(() => {
          try {
            const myModuleInstallProvider: moduleInstallManager.ModuleInstallProvider =
              new moduleInstallManager.ModuleInstallProvider();
            const context: common.UIAbilityContext | common.ExtensionContext = this.getUIContext().getHostContext() as common.UIAbilityContext;
            // Create an on-demand loading request object.
            const myModuleInstallRequest: moduleInstallManager.ModuleInstallRequest =
              myModuleInstallProvider.createModuleInstallRequest(context);
            // Add the name of the module to be loaded.
            myModuleInstallRequest.addModule('AModule');
            myModuleInstallRequest.addModule('BModule');
            // API for requesting on-demand loading, which returns the results of calling the APIs for initiating requests, registering listeners, and unregistering listeners.
            moduleInstallManager.fetchModules(myModuleInstallRequest)
              .then((result: moduleInstallManager.ModuleInstallSessionState) => {
                if (result.code === moduleInstallManager.RequestErrorCode.SUCCESS) {
                  hilog.info(0, TAG, 'Succeeded in fetching modules success data.' );
                } else {
                  hilog.info(0, TAG, 'Fetching modules failed' );
                }
              })
          } catch (error) {
            hilog.error(0, TAG, `fetching modules onError.code is ${error.code}, message is ${error.message}`);
          }
        })
        .width('100%')
    }
    .margin(16)
    .height('100%')
    .justifyContent(FlexAlign.Center)
  }
}

moduleInstallManager.cancelTask

cancelTask(taskId: string): ReturnCode

Cancels a download task.

Model restriction: This API can be used only in the stage model.

System capability: SystemCapability.AppGalleryService.Distribution.OnDemandInstall

Since: 4.1.0(11)

Parameters:

Parameter Type Mandatory Description
taskId string Yes ID of the download task.

Returns:

Type Description
ReturnCode API call result code.

Error codes:

For details about the error codes, please refer to ArkTS API Error Codes.

Error Code Error Message
401 Parameter error.
1006500007 The specified service extension connect failed.
1006500008 Write param into container failed.
1006500009 Request to service error.
1006500010 Response from service cannot be recognized.

Example:

import { moduleInstallManager } from '@kit.AppGalleryKit';
import { hilog } from '@kit.PerformanceAnalysisKit';

try {
  // taskId is a field in ModuleInstallSessionState returned by fetchModules.
  const taskId: string = '********';
  const rtnCode: moduleInstallManager.ReturnCode = moduleInstallManager.cancelTask(taskId);
  hilog.info(0, 'TAG', "Succeeded in getting result:" + rtnCode);
} catch (error) {
  hilog.error(0, 'TAG', `cancelTask onError.code is ${error.code}, message is ${error.message}`);
}

moduleInstallManager.showCellularDataConfirmation

showCellularDataConfirmation(context: common.UIAbilityContext | common.ExtensionContext,taskId: string): ReturnCode

Displays a mobile data reminder pop-up.

Model restriction: This API can be used only in the stage model.

System capability: SystemCapability.AppGalleryService.Distribution.OnDemandInstall

Since: 4.1.0(11)

Parameters:

Parameter Type Mandatory Description
context common.UIAbilityContext | common.ExtensionContext Yes Context. Currently, only UIAbilityContext and ExtensionContext are supported. UIAbilityContext is used to check whether the current app is running in the foreground.
taskId string Yes ID of the download task.

Returns:

Type Description
ReturnCode API call result code.

Error codes:

For details about the error codes, please refer to ArkTS API Error Codes.

Error Code Error Message
401 Parameter error.
1006500007 The specified service extension connect failed.
1006500008 Write param into container failed.
1006500009 Request to service error.
1006500010 Response from service cannot be recognized.

Example:

import { common } from '@kit.AbilityKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
import { moduleInstallManager } from '@kit.AppGalleryKit';

const TAG: string = 'showCellularDataConfirmation';

@Entry
@Component
struct ShowCellularDataConfirmation {

  build() {
    Column() {
      Button("showCellularDataConfirmation")
        .onClick(() => {
          try {
            // taskId is a field in ModuleInstallSessionState returned by fetchModules.
            const taskId: string = '********';
            const context = this.getUIContext().getHostContext()  as common.UIAbilityContext;
            const rtnCode: moduleInstallManager.ReturnCode =
              moduleInstallManager.showCellularDataConfirmation(context, taskId);
            hilog.info(0, TAG, "Succeeded in getting result:" + rtnCode);
          } catch (error) {
            hilog.error(0, TAG, `showCellularDataConfirmation onError.code is ${error.code}, message is ${error.message}`);
          }
        })
        .width('100%')
    }
    .margin(16)
    .height('100%')
    .justifyContent(FlexAlign.Center)
  }
}

moduleInstallManager.on('moduleInstallStatus')

on(type: 'moduleInstallStatus', callback: Callback<ModuleInstallSessionState>, timeout: number): void

Listens for the progress of the current app download task. Multi-threaded calls are not supported. When a module is being loaded, the callback function is used to notify the caller. If the installation is successful and the app is in debug mode, the debug files in the path of the successfully installed module will be deleted.

Model restriction: This API can be used only in the stage model.

System capability: SystemCapability.AppGalleryService.Distribution.OnDemandInstall

Since: 4.1.0(11)

Parameters:

Parameter Type Mandatory Description
type string Yes The value is always moduleInstallStatus.
callback Callback<ModuleInstallSessionState> Yes Callback used to return the result.
timeout number Yes Maximum listening duration supported by the registered listener, in seconds. The default duration is 30 minutes (30 x 60s). If the value exceeds 30 minutes, it is considered as 30 minutes.

Error codes:

For details about the error codes, please refer to ArkTS API Error Codes.

Error Code Error Message
401 Parameter error.
1006500002 The interface is called repeatedly with the same input.
1006500004 SA connection failed.

Example:

import { moduleInstallManager } from '@kit.AppGalleryKit';
import { hilog } from '@kit.PerformanceAnalysisKit';

try {
  const timeout = 30 * 60;
  moduleInstallManager.on('moduleInstallStatus', (data: moduleInstallManager.ModuleInstallSessionState) => {
    // Register a listener.
    hilog.info(0, 'TAG', 'Succeeded in getting moduleInstallManager.on.' );
  }, timeout)
} catch (error) {
  hilog.error(0, 'TAG', `moduleInstallManager.on onError.code is ${error.code}, message is ${error.message}`);
}

moduleInstallManager.off('moduleInstallStatus')

off(type: 'moduleInstallStatus', callback?: Callback<ModuleInstallSessionState>): void

Cancels the listener of the current app download task's progress. Multi-threaded calls are not supported.

Model restriction: This API can be used only in the stage model.

System capability: SystemCapability.AppGalleryService.Distribution.OnDemandInstall

Since: 4.1.0(11)

Parameters:

Parameter Type Mandatory Description
type string Yes The value is always moduleInstallStatus.
callback Callback<ModuleInstallSessionState> No Callback used to return the result. If this parameter is left empty, all listeners of the current app will be canceled.

Error codes:

For details about the error codes, please refer to ArkTS API Error Codes.

Error Code Error Message
401 Parameter error.
1006500004 SA connection failed.
1006500006 The interface is not used together with "on".

Example:

import { moduleInstallManager } from '@kit.AppGalleryKit';
import { hilog } from '@kit.PerformanceAnalysisKit';

try {
  moduleInstallManager.off('moduleInstallStatus', (data: moduleInstallManager.ModuleInstallSessionState) => {
    // Cancel the listener.
    hilog.info(0, 'TAG', 'Succeeded in getting moduleInstallManager.off.' );
  })
} catch (error) {
  hilog.error(0, 'TAG', `moduleInstallManager.off onError.code is ${error.code}, message is ${error.message}`);
}

moduleInstallManager.pauseTask

pauseTask(taskId: string): ReturnCode

Pauses a download task.

Model restriction: This API can be used only in the stage model.

System capability: SystemCapability.AppGalleryService.Distribution.OnDemandInstall

Since: 26.0.0

Parameters:

Parameter Type Mandatory Description
taskId string Yes ID of the download task.

Returns:

Type Description
ReturnCode API call result code.

Error codes:

For details about the error codes, please refer to ArkTS API Error Codes.

Error Code Error Message
1006500012 Internal communication error.
1006500013 Invalid taskId.

Example:

import { hilog } from '@kit.PerformanceAnalysisKit';
import { moduleInstallManager } from '@kit.AppGalleryKit';

const TAG: string = 'pauseTask';

@Entry
@Component
struct PauseTask {

  build() {
    Column() {
      Button("pauseTask")
        .onClick(() => {
          try {
            const taskId: string = '********';
            // Pause a download task.
            const rtnCode: moduleInstallManager.ReturnCode = moduleInstallManager.pauseTask(taskId);
            hilog.info(0, 'TAG', "Succeeded in getting result:" + rtnCode);
          } catch (error) {
            hilog.error(0, TAG, `pauseTask onError.code is ${error.code}, message is ${error.message}`);
          }
        })
        .width('100%')
    }
    .margin(16)
    .height('100%')
    .justifyContent(FlexAlign.Center)
  }
}