1# UIAbility Lifecycle
2
3
4## Overview
5
6When a user opens or switches to and from an application, the [UIAbility](../reference/apis-ability-kit/js-apis-app-ability-uiAbility.md) instances in the application transit in their different states. The UIAbility class provides a series of callbacks. Through these callbacks, you can know the state changes of the UIAbility instance.
7
8The lifecycle of UIAbility has four states: **Create**, **Foreground**, **Background**, and **Destroy**, as shown in the figure below.
9
10**Figure 1** UIAbility lifecycle states
11
12![Ability-Life-Cycle](figures/Ability-Life-Cycle.png)  
13
14
15## Description of Lifecycle States
16
17
18### Create
19
20The **Create** state is triggered when the [UIAbility](../reference/apis-ability-kit/js-apis-app-ability-uiAbility.md) instance is created during application loading. It corresponds to the [onCreate()](../reference/apis-ability-kit/js-apis-app-ability-uiAbility.md#uiabilityoncreate) callback. In this callback, you can perform page initialization operations, for example, defining variables or loading resources.
21
22
23```ts
24import { AbilityConstant, UIAbility, Want } from '@kit.AbilityKit';
25
26export default class EntryAbility extends UIAbility {
27  onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void {
28    // Initialize the page.
29  }
30  // ...
31}
32```
33
34> **NOTE**
35>
36> [Want](../reference/apis-ability-kit/js-apis-app-ability-want.md) is used as the carrier to transfer information between application components. For details, see [Want](want-overview.md).
37
38### WindowStageCreate and WindowStageDestroy
39
40After the [UIAbility](../reference/apis-ability-kit/js-apis-app-ability-uiAbility.md) instance is created but before it enters the Foreground state, the system creates a WindowStage instance and triggers the [onWindowStageCreate()](../reference/apis-ability-kit/js-apis-app-ability-uiAbility.md#uiabilityonwindowstagecreate) callback. You can set UI loading and WindowStage event subscription in the callback.
41
42**Figure 2** WindowStageCreate and WindowStageDestroy 
43
44![Ability-Life-Cycle-WindowStage](figures/Ability-Life-Cycle-WindowStage.png)  
45
46In the **onWindowStageCreate()** callback, use [loadContent()](../reference/apis-arkui/js-apis-window.md#loadcontent9) to set the page to be loaded, and call [on('windowStageEvent')](../reference/apis-arkui/js-apis-window.md#onwindowstageevent9) to subscribe to [WindowStage events](../reference/apis-arkui/js-apis-window.md#windowstageeventtype9), for example, having or losing focus, or becoming visible or invisible.
47
48```ts
49import { UIAbility } from '@kit.AbilityKit';
50import { window } from '@kit.ArkUI';
51import { hilog } from '@kit.PerformanceAnalysisKit';
52
53const TAG: string = '[EntryAbility]';
54const DOMAIN_NUMBER: number = 0xFF00;
55
56export default class EntryAbility extends UIAbility {
57  // ...
58  onWindowStageCreate(windowStage: window.WindowStage): void {
59    // Subscribe to the WindowStage events (having or losing focus, or becoming visible or invisible).
60    try {
61      windowStage.on('windowStageEvent', (data) => {
62        let stageEventType: window.WindowStageEventType = data;
63        switch (stageEventType) {
64          case window.WindowStageEventType.SHOWN: // Switch to the foreground.
65            hilog.info(DOMAIN_NUMBER, TAG, 'windowStage foreground.');
66            break;
67          case window.WindowStageEventType.ACTIVE: // Gain focus.
68            hilog.info(DOMAIN_NUMBER, TAG, 'windowStage active.');
69            break;
70          case window.WindowStageEventType.INACTIVE: // Lose focus.
71            hilog.info(DOMAIN_NUMBER, TAG, 'windowStage inactive.');
72            break;
73          case window.WindowStageEventType.HIDDEN: // Switch to the background.
74            hilog.info(DOMAIN_NUMBER, TAG, 'windowStage background.');
75            break;
76          default:
77            break;
78        }
79      });
80    } catch (exception) {
81      hilog.error(DOMAIN_NUMBER, TAG, 'Failed to enable the listener for window stage event changes. Cause:' + JSON.stringify(exception));
82    }
83    hilog.info(DOMAIN_NUMBER, TAG, '%{public}s', 'Ability onWindowStageCreate');
84    // Set the page to be loaded.
85    windowStage.loadContent('pages/Index', (err, data) => {
86      // ...
87    });
88  }
89}
90```
91
92> **NOTE**
93>
94> For details about how to use WindowStage, see [Window Development](../windowmanager/application-window-stage.md).
95
96Before the [UIAbility](../reference/apis-ability-kit/js-apis-app-ability-uiAbility.md) instance is destroyed, the [onWindowStageDestroy()](../reference/apis-ability-kit/js-apis-app-ability-uiAbility.md#uiabilityonwindowstagedestroy) callback is invoked to release UI resources.
97
98```ts
99import { UIAbility } from '@kit.AbilityKit';
100import { window } from '@kit.ArkUI';
101import { hilog } from '@kit.PerformanceAnalysisKit';
102import { BusinessError } from '@kit.BasicServicesKit';
103
104const TAG: string = '[EntryAbility]';
105const DOMAIN_NUMBER: number = 0xFF00;
106
107export default class EntryAbility extends UIAbility {
108  windowStage: window.WindowStage | undefined = undefined;
109
110  // ...
111  onWindowStageCreate(windowStage: window.WindowStage): void {
112    this.windowStage = windowStage;
113    // ...
114  }
115
116  onWindowStageDestroy() {
117    // Release UI resources.
118    // Unsubscribe from the WindowStage events such as having or losing focus in the onWindowStageDestroy() callback.
119    try {
120      if (this.windowStage) {
121        this.windowStage.off('windowStageEvent');
122      }
123    } catch (err) {
124      let code = (err as BusinessError).code;
125      let message = (err as BusinessError).message;
126      hilog.error(DOMAIN_NUMBER, TAG, `Failed to disable the listener for windowStageEvent. Code is ${code}, message is ${message}`);
127    }
128  }
129}
130```
131
132### WindowStageWillDestroy
133The [onWindowStageWillDestroy()](../reference/apis-ability-kit/js-apis-app-ability-uiAbility.md#uiabilityonwindowstagewilldestroy12) callback is invoked before the window stage is destroyed. In this case, the window stage can still be used.
134
135```ts
136import { UIAbility } from '@kit.AbilityKit';
137import { window } from '@kit.ArkUI';
138
139export default class EntryAbility extends UIAbility {
140  windowStage: window.WindowStage | undefined = undefined;
141  // ...
142  onWindowStageCreate(windowStage: window.WindowStage): void {
143    this.windowStage = windowStage;
144    // ...
145  }
146  onWindowStageWillDestroy(windowStage: window.WindowStage) {
147    // Release the resources obtained through the windowStage object.
148  }
149  onWindowStageDestroy() {
150    // Release UI resources.
151  }
152}
153```
154
155> **NOTE**
156>
157> For details about how to use WindowStage, see [Window Development](../windowmanager/application-window-stage.md).
158
159
160### Foreground and Background
161
162The **Foreground** and **Background** states are triggered when the [UIAbility](../reference/apis-ability-kit/js-apis-app-ability-uiAbility.md) instance is switched to the foreground and background, respectively. They correspond to the [onForeground()](../reference/apis-ability-kit/js-apis-app-ability-uiAbility.md#uiabilityonforeground) and [onBackground()](../reference/apis-ability-kit/js-apis-app-ability-uiAbility.md#uiabilityonbackground) callbacks.
163
164The **onForeground()** callback is triggered when the UI of the UIAbility instance is about to become visible, for example, when the UIAbility instance is about to enter the foreground. In this callback, you can apply for resources required by the system or re-apply for resources that have been released in the **onBackground()** callback.
165
166The **onBackground()** callback is triggered when the UI of the UIAbility instance is about to become invisible, for example, when the UIAbility instance is about to enter the background. In this callback, you can release unused resources or perform time-consuming operations such as saving the status.
167
168For example, there is an application that requires location access and has obtained the location permission from the user. Before the UI is displayed, you can enable location in the **onForeground()** callback to obtain the location information.
169
170When the application is switched to the background, you can disable location in the **onBackground()** callback to reduce system resource consumption.
171
172
173```ts
174import { UIAbility } from '@kit.AbilityKit';
175
176export default class EntryAbility extends UIAbility {
177  // ...
178
179  onForeground(): void {
180    // Apply for the resources required by the system or re-apply for the resources released in onBackground().
181  }
182
183  onBackground(): void {
184    // Release unused resources when the UI is invisible, or perform time-consuming operations in this callback,
185    // for example, saving the status.
186  }
187}
188```
189
190Assume that the application already has a UIAbility instance created, and the launch type of the UIAbility instance is set to [singleton](uiability-launch-type.md#singleton). If [startAbility()](../reference/apis-ability-kit/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability) is called again to start the UIAbility instance, the [onNewWant()](../reference/apis-ability-kit/js-apis-app-ability-uiAbility.md#uiabilityonnewwant) callback is invoked, but the [onCreate()](../reference/apis-ability-kit/js-apis-app-ability-uiAbility.md#uiabilityoncreate) and [onWindowStageCreate()](../reference/apis-ability-kit/js-apis-app-ability-uiAbility.md#uiabilityonwindowstagecreate) callbacks are not. The application can update the resources and data to be loaded in the callback, which will be used for UI display.
191
192```ts
193import { AbilityConstant, UIAbility, Want } from '@kit.AbilityKit';
194
195export default class EntryAbility extends UIAbility {
196  // ...
197
198  onNewWant(want: Want, launchParam: AbilityConstant.LaunchParam) {
199    // Update resources and data.
200  }
201}
202```
203
204### Destroy
205
206The Destroy state is triggered when the [UIAbility](../reference/apis-ability-kit/js-apis-app-ability-uiAbility.md) instance is destroyed. You can perform operations such as releasing system resources and saving data in the **onDestroy()** callback.
207
208The UIAbility instance is destroyed when [terminateSelf()](../reference/apis-ability-kit/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextterminateself) is called and the **onDestroy()** callback is invoked.
209<!--RP1-->The UIAbility instance is also destroyed when the user closes the instance in the system application Recents and the **onDestroy()** callback is invoked.<!--RP1End-->
210
211```ts
212import { UIAbility } from '@kit.AbilityKit';
213
214export default class EntryAbility extends UIAbility {
215  // ...
216
217  onDestroy() {
218    // Release system resources and save data.
219  }
220}
221```
222