DEV Community

zhonghua
zhonghua

Posted on • Edited on

HarmonyOS Development in Practice: Unveiling Page and Project Lifecycle for Precise Monitoring

HarmonyOS Development in Practice: Unveiling Page and Project Lifecycle for Precise Monitoring

Preface

In HarmonyOS application development, every page and component has a specific lifecycle. These lifecycle stages, like the trajectory of life, record every important moment from the birth to the demise of a page. A deep understanding and monitoring of these lifecycles can not only enhance application performance but also help us better grasp the user experience.

  1. Detailed Explanation of HarmonyOS @Component Lifecycle

In HarmonyOS's ArkTS framework, custom components have two crucial lifecycle functions: aboutToAppear() and aboutToDisappear(). These functions are automatically called by the system when the component is about to appear and disappear, respectively, providing developers with the opportunity to perform specific operations at specific times.

  • aboutToAppear(): Executed before the component's build() function, it is an ideal time for data initialization and resource loading.
  • aboutToDisappear(): Called when the component is about to be destroyed, it is suitable for cleanup tasks such as removing event listeners and releasing resources.

Component Lifecycle Flowchart

+-----------------+
| ArkTS Component |
+-----------------+
    |
    | Initialize Data
    V
+------------+
| aboutToAppear() |
+------------+
    |
    | Component Construction and Rendering
    V
(build() and other logic)
    |
    | User Interaction
    | ...
    V
+-----------------+
| aboutToDisappear() |
+-----------------+
    |
    | Preparations Before Component Destruction
    V
(Component is destroyed)
Enter fullscreen mode Exit fullscreen mode

Code in Practice

Here is a simple example demonstrating how to use these two lifecycle functions in a HarmonyOS component:

// CustomComponent.ets
@Entry
@Component
export default struct CustomComponent {

  // Called when the component is about to appear
  aboutToAppear() {
    console.log('CustomComponent: aboutToAppear called. Component is about to appear.');
    // Perform data initialization here
  }

  // Called when the component is about to disappear
  aboutToDisappear() {
    console.log('CustomComponent: aboutToDisappear called. Component is about to disappear.');
    // Perform cleanup operations here
  }

  build() {
    // Component construction and rendering logic
    Flex({ direction: FlexDirection.Column, justifyContent: FlexAlign.Center, alignItems: ItemAlign.Center }) {
      Text('This is a CustomComponent').fontSize(24).margin({ top: 20 })
      // Other components or layouts...
    }.width('100%').height('100%')
  }
}
Enter fullscreen mode Exit fullscreen mode

In-Depth Exploration

By precisely controlling and managing the component lifecycle, we can achieve more efficient application development and a smoother user experience. Additionally, combining APM performance monitoring tools allows us to perform real-time analysis and optimization of the application, ensuring it always runs at its best.

  1. In-Depth Analysis of Page Entry Component Lifecycle

In HarmonyOS development, page entry components play a crucial role. These components, decorated with @Entry, not only have the regular component lifecycle functions but also provide three additional page entry-specific lifecycle functions: onPageShow(), onBackPress(), and onPageHide(). These functions enable developers to more precisely control the behavior of pages in different states.

Lifecycle Function Details

  • onPageShow(): Executed when the software enters the page. At this point, the page has completed construction and rendering and is ready to be displayed to the user. This is an ideal time for page data loading and animation startup.
  • onBackPress(): Executed when the user clicks the back button or performs other back operations. Developers can perform cleanup tasks here, such as saving user input and confirming whether the user really wants to leave the page.
  • onPageHide(): Executed when the user presses the Home button to return to the phone's main interface or performs other operations that cause the page to hide. At this point, the page remains in memory but is no longer visible to the user. Developers can pause unnecessary background operations here to save system resources.

If the application is completely destroyed (e.g., the user manually exits the application or the system terminates the application due to insufficient memory), the aboutToDisappear() function is called. Unlike onPageHide(), aboutToDisappear() indicates that the component is about to be completely destroyed and no longer retained in memory. Therefore, developers should perform necessary cleanup tasks here, such as releasing resources and removing event listeners.

Lifecycle Flowchart

+------------------+
| @Entry Component |
+------------------+
    |
    | Page is about to appear
    V
+-----------------+
| aboutToAppear() |
+-----------------+
    |
    | Component Construction and Rendering
    V
+------------+
| build()      |
+------------+
    |
    | Page display completed
    V
+-------------+
| onPageShow() |
+-------------+
    |
    | User interaction and operations
    | ...
    V
+----------------+
| User operations or interactions |
+----------------+
    |
    | User clicks the back button or leaves the page
    V
+--------------+
| onBackPress() |
+--------------+
    |
    | Page hidden
    V
+--------------+
| onPageHide()  |
+--------------+
    |
    | Application destroyed or page no longer needed
    V
+-----------------+
| aboutToDisappear() |
+-----------------+
    |
    | Component is destroyed
    V
(Component is completely removed from memory)
Enter fullscreen mode Exit fullscreen mode

Practical Guide

  • Utilize Lifecycle Functions Appropriately: Perform corresponding operations in the appropriate lifecycle functions based on the needs of the page and component. For example, load data in onPageShow() and pause background tasks in onPageHide().
  • Pay Attention to Resource Management: Ensure that all unnecessary resources are released in aboutToDisappear() to avoid memory leaks and performance issues.
  • User Interaction and Navigation: Handle user back operations in onBackPress() to ensure smooth navigation and page exit for users.

By deeply understanding and effectively utilizing the lifecycle functions of page entry components, we can create more efficient, smooth, and user-friendly HarmonyOS applications.

  1. Analysis of UIAbility Lifecycle

Detailed Explanation of Lifecycle States

https://i-blog.csdnimg.cn/blog_migrate/ad4990e53d7189f3246b50a4b0a98672.png

Create State

The Create state is triggered during the application loading process when the UIAbility instance is created. The system calls the onCreate() callback method. In this callback method, developers can perform page initialization operations, such as variable definition and resource loading, to prepare for subsequent UI display.

import AbilityConstant from '@ohos.app.ability.AbilityConstant';
import UIAbility from '@ohos.app.ability.UIAbility';
import Want from '@ohos.app.ability.Want';

export default class EntryAbility extends UIAbility {
    onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void {
        // Page initialization, such as loading data and setting initial states
    }
    // ... other methods
}
Enter fullscreen mode Exit fullscreen mode

WindowStageCreate State

After the UIAbility instance is created but before entering the foreground (Foreground) display, the system creates a WindowStage. WindowStage is an abstract representation of the application window, which includes window rendering, event handling, and other functionalities.

When the WindowStage is created, the system calls the onWindowStageCreate() callback method. In this callback method, developers can set up the project configuration and the home page to jump to. In this way, when the WindowStage enters the foreground display, the application is ready with the UI content to display and the ability to handle user interactions.


export default class EntryAbility extends UIAbility {
    // ... other methods

onWindowStageCreate(windowStage: window.WindowStage): void {
  const applicationContext = this.context.getApplicationContext()
  // Loading starts
  let entryPage = 'pages/main/IndexPage'
  // Load configuration
  let config = ...
  }

    // ... other methods
}
Enter fullscreen mode Exit fullscreen mode

Practical Guide

  1. Configure Basic Project Data: Basic project configuration can be done in the onWindowStageCreate function.
  2. Event Subscription and Handling: Subscribe to some lifecycle functions in onWindowStageCreate.

  3. Monitoring and Subscription

In EntryAbility, we usually need to listen for changes in the application state and Ability lifecycle events. By listening to these events, we can better manage resources, execute specific logic, and optimize the user experience.

EntryAbility Class

// The EntryAbility class extends UIAbility to manage the application lifecycle and event listening
export default class EntryAbility extends UIAbility {
    // Used to save the Ability Lifecycle listener ID
    private lifecycleId: number = -1;

    // Triggered when WindowStage is created
    onWindowStageCreate(windowStage: window.WindowStage): void {
        // Get application context
        const applicationContext = this.context.getApplicationContext();

        // Listen for application state changes
        // Create an instance of EntryApplicationStateChangeCallback to handle state changes
        applicationContext.on('applicationStateChange', new EntryApplicationStateChangeCallback());

        // Listen for Ability Lifecycle events
        // Create an instance of EntryAbilityLifecycleCallback and get the listener ID
        this.lifecycleId = applicationContext.on('abilityLifecycle', new EntryAbilityLifecycleCallback());

        // Initialization operations after WindowStage creation can be performed here
        // ...
    }

    // Triggered when Ability is destroyed
    onDestroy(): void {
        // Get application context
        const applicationContext = this.context.getApplicationContext();

        // Unsubscribe from application state changes
        applicationContext.off('applicationStateChange');

        // If there is an Ability Lifecycle listener ID, unsubscribe from the listener
        if (this.lifecycleId !== -1) {
            applicationContext.off('abilityLifecycle', this.lifecycleId);
        }

        // Cleanup resources and release memory operations can be performed here
        // ...
    }

    // ... other methods
}
Enter fullscreen mode Exit fullscreen mode

EntryAbilityLifecycleCallback Class

// The EntryAbilityLifecycleCallback class extends AbilityLifecycleCallback to handle Ability lifecycle events
export default class EntryAbilityLifecycleCallback extends AbilityLifecycleCallback {
    // Triggered when Ability is created
    onAbilityCreate(ability: UIAbility): void {
        // Initialization operations after Ability creation can be performed here
        // ...
    }

    // Triggered when WindowStage is created
    onWindowStageCreate(ability: UIAbility, windowStage: window.WindowStage): void {
        // Initialization operations after WindowStage creation can be performed here
        // ...
    }

    // Triggered when the page gains focus
    onWindowStageActive(ability: UIAbility, windowStage: window.WindowStage): void {
        // Operations when the page is activated, such as resuming state and refreshing data, can be performed here
        // ...
    }

    // Triggered when WindowStage loses focus
    onWindowStageInactive(ability: UIAbility, windowStage: window.WindowStage): void {
        // Operations when the page loses focus, such as pausing animations and saving state, can be performed here
        // ...
    }

    // Triggered when WindowStage is destroyed
    onWindowStageDestroy(ability: UIAbility, windowStage: window.WindowStage): void {
        // Cleanup operations before WindowStage destruction can be performed here
        // ...
    }

    // Triggered when Ability is destroyed
    onAbilityDestroy(ability: UIAbility): void {
        // Cleanup operations before Ability destruction can be performed here
        // ...
    }

    // Triggered when Ability enters the foreground
    onAbilityForeground(ability: UIAbility): void {
        // Operations when Ability enters the foreground, such as resuming paused animations, can be performed here
        // ...
    }

    // Triggered when Ability enters the background
    onAbilityBackground(ability: UIAbility): void {
        // Operations when Ability enters the background, such as pausing animations and saving state, can be performed here
        // ...
    }

    // Triggered when Ability resumes from a paused state
    onAbilityContinue(ability: UIAbility): void {
        // Operations when Ability resumes, such as continuing animations, can be performed here
        // ...
    }
}
Enter fullscreen mode Exit fullscreen mode

EntryApplicationStateChangeCallback Class

// The EntryApplicationStateChangeCallback class extends ApplicationStateChangeCallback to handle application state change events
export default class EntryApplicationStateChangeCallback extends ApplicationStateChangeCallback {
    // Triggered when the application enters the foreground
    onApplicationForeground(): void {
        // Operations when the application enters the foreground, such as resuming network requests, can be performed here
        // ...
    }

    // Triggered when the application enters the background
    onApplicationBackground(): void {
        // Operations when the application enters the background, such as pausing animations and stopping network requests, can be performed here
        // ...
    }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)