harmony 鸿蒙AbilityStage Component Container

  • 2023-02-03
  • 浏览 (1123)

AbilityStage Component Container

Overview

AbilityStage is a component container at the module level. When the HAP of an application is loaded for the first time, an AbilityStage instance is created. You can perform operations such as initialization on the instance. An AbilityStage instance corresponds to a module.

AbilityStage has the lifecycle callbacks onCreate() and onDestroy() and the event callbacks onAcceptWant(), onConfigurationUpdate(), and onMemoryLevel().

  • onCreate() lifecycle callback: Before the first UIAbility instance of a module is loaded, an AbilityStage instance is created. This callback is invoked when the AbilityStage instance is created. The AbilityStage module notifies you of when you can perform module initialization such as resource pre-loading and thread creation during module loading.

  • onAcceptWant() event callback: triggered when the UIAbility is started in specified mode. For details, see UIAbility Component Launch Type.

  • onConfigurationUpdate() event callback: triggered when the global system configuration changes. The global system configuration, such as the system language and theme, are defined in the Configuration class before project configuration.

  • onMemoryLevel() event callback: triggered when the system adjusts the memory. When an application is switched to the background, it is cached in the background. This adversely affects the overall system performance. When system resources are insufficient, the system reclaims memory from applications in multiple ways. For example, the system may stop applications to release memory for executing key tasks. To further maintain the balance of the system memory and prevent the system from stopping application processes, you can subscribe to the system memory changes in the onMemoryLevel() lifecycle callback of AbilityStage to release unnecessary resources.

  • onDestroy(): called when an application is destroyed. This callback is triggered only when the application is destroyed normally. It is not triggered if the application exits abnormally or is terminated.

How to Develop

Creating an AbilityStage File

AbilityStage is not automatically generated in the default project of DevEco Studio. To use AbilityStage, you can manually create an AbilityStage file. The procedure is as follows:

  1. In the ets directory of the Module project, right-click and choose New > Directory to create a directory named myabilitystage.

  2. In the myabilitystage directory, right-click and choose New > ArkTS File to create a file named MyAbilityStage.ets.

  3. Open the MyAbilityStage.ets file, and import the dependency package of AbilityStage. Customize a class that inherits from AbilityStage, and add the required lifecycle callbacks. The following code snippet adds the onCreate() lifecycle callback.

    import { AbilityStage, Want } from '@kit.AbilityKit';
    
    
    export default class MyAbilityStage extends AbilityStage {
      onCreate(): void {
        // This callback is triggered when the HAP is loaded for the first time. In this callback, you can initialize the module (for example, pre-load resources and create threads).
      }
    
    
      onAcceptWant(want: Want): string {
        // Triggered only for the UIAbility with the specified launch type.
        return 'MyAbilityStage';
      }
    }
    
  4. In the module.json5 file, set srcEntry to specify the code path of the module as the entry for loading the HAP.

    {
      "module": {
        "name": "entry",
        "type": "entry",
        "srcEntry": "./ets/myabilitystage/MyAbilityStage.ets",
        // ...
      }
    }
    

Listening for System Environment Variable Changes

Here is an example of how to use the callback functions of the AbilityStage component to track changes in system environment variables.

  • In the onCreate() lifecycle, use EnvironmentCallback to listen for system environment changes, such as the system language, light/dark mode, screen orientation, font size scaling factor, and font weight scaling factor.

  • When the global system configuration changes, the onConfigurationUpdated() callback in EnvironmentCallback is triggered and related information is logged.

  • When the application process is terminated, the onDestroy() callback of the AbilityStage component is triggered.

    import { EnvironmentCallback, AbilityStage } from '@kit.AbilityKit';
    import { BusinessError } from '@kit.BasicServicesKit';
    
    
    export default class MyAbilityStage extends AbilityStage {
      onCreate(): void {
        console.log('AbilityStage onCreate');
        let envCallback: EnvironmentCallback = {
          onConfigurationUpdated(config) {
            console.info(`envCallback onConfigurationUpdated success: ${JSON.stringify(config)}`);
            let language = config.language; // Current language of the application.
            let colorMode = config.colorMode; // Dark/Light mode.
            let direction = config.direction; // Screen orientation.
            let fontSizeScale = config.fontSizeScale; // Font size scaling factor.
            let fontWeightScale = config.fontWeightScale; // Font weight scaling factor.
          },
          onMemoryLevel(level) {
            console.log(`onMemoryLevel level: ${level}`);
          }
        };
        try {
          let applicationContext = this.context.getApplicationContext();
          let callbackId = applicationContext.on('environment', envCallback);
          console.log(`callbackId: ${callbackId}`);
        } catch (paramError) {
          console.error(`error: ${(paramError as BusinessError).code}, ${(paramError as BusinessError).message}`);
        }
      }
    
    
      onDestroy(): void {
        // Use onDestroy() to listen for the ability destruction event.
        console.log('AbilityStage onDestroy');
      }
    }
    

你可能感兴趣的鸿蒙文章

harmony 鸿蒙Ability Kit

harmony 鸿蒙Obtaining Reasons for Abnormal Application Exits

harmony 鸿蒙UIAbility Backup and Restore

harmony 鸿蒙Using Explicit Want to Start an Application Component

harmony 鸿蒙Introduction to Ability Kit

harmony 鸿蒙Accessing a DataAbility

harmony 鸿蒙Accessing a DataShareExtensionAbility from the FA Model

harmony 鸿蒙Common action and entities Values (Not Recommended)

harmony 鸿蒙API Switching Overview

harmony 鸿蒙Switching of app and deviceConfig

0  赞