1# UIAbility Lifecycle 2 3<!--Kit: Ability Kit--> 4<!--Subsystem: Ability--> 5<!--Owner: @altay; @Luobniz21--> 6<!--Designer: @altay--> 7<!--Tester: @lixueqing513--> 8<!--Adviser: @huipeizi--> 9 10## Overview 11 12Whenever a user launches, pauses, resumes, or exits an application, the system fires a set of lifecycle callbacks. For a UIAbility—the component that provides UI—the key callbacks are [onCreate](../reference/apis-ability-kit/js-apis-app-ability-uiAbility.md#oncreate), [onForeground](../reference/apis-ability-kit/js-apis-app-ability-uiAbility.md#onforeground), [onBackground](../reference/apis-ability-kit/js-apis-app-ability-uiAbility.md#onbackground) and [onDestroy](../reference/apis-ability-kit/js-apis-app-ability-uiAbility.md#ondestroy). The UIAbility lifecycle is closely linked to the [WindowStage](../../application-dev/windowmanager/application-window-stage.md) lifecycle. 13 14The following figure illustrates the UIAbility lifecycle. 15 16 17 18The following describes the UIAbility launch scenarios and lifecycle callback processes. 19 20- The UIAbility is launched to the foreground. The corresponding process flow is shown in the diagram above. 21 22 1. When a user launches a UIAbility, the system sequentially triggers the **onCreate()**, **onWindowStageCreate()**, and **onForeground()** lifecycle callbacks. 23 24 2. When the user switches to another application (moving the current UIAbility to the background), the system triggers the **onBackground()** lifecycle callback. 25 26 3. When the user brings the UIAbility back to the foreground, the system sequentially triggers the **onNewWant()** and **onForeground()** lifecycle callbacks. 27 28- The UIAbility is launched to the background. The corresponding process flow is shown in the diagram below. 29 30 1. When a user starts a UIAbility in the background by calling [UIAbilityContext.startAbilityByCall()](../reference/apis-ability-kit/js-apis-inner-application-uiAbilityContext.md#startabilitybycall), the system sequentially triggers the **onCreate()** and **onBackground()** lifecycle callbacks (the **onWindowStageCreate()** lifecycle callback is not executed). 31 32 2. When the user brings the UIAbility to the foreground, the system sequentially triggers the **onNewWant()**, **onWindowStageCreate()**, and **onForeground()** lifecycle callbacks. 33 34  35 36## Lifecycle Callbacks 37 38> **NOTE** 39> 40> - Lifecycle callbacks are executed on the main thread of an application. To ensure application performance, you are advised to perform only necessary lightweight operations in lifecycle callbacks. For time-consuming tasks, you are advised to process them asynchronously or dispatch them to a child thread. 41> - To detect lifecycle changes of a UIAbility, register a global listener via [ApplicationContext.onAbilityLifecycle()](../reference/apis-ability-kit/js-apis-inner-application-applicationContext.md#applicationcontextonabilitylifecycle). For details, see [Listening for UIAbility Lifecycle Changes](./application-context-stage.md#listening-for-uiability-lifecycle-changes). 42 43### onCreate() 44 45The system triggers the [onCreate()](../reference/apis-ability-kit/js-apis-app-ability-uiAbility.md#oncreate) callback when the UIAbility instance is created for the first time. Within this callback, you can execute the startup logic that only occurs once during the entire lifecycle of the UIAbility. 46 47```ts 48import { AbilityConstant, UIAbility, Want } from '@kit.AbilityKit'; 49 50export default class EntryAbility extends UIAbility { 51 onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void { 52 // Execute the service logic that occurs only once during the entire lifecycle of the UIAbility. 53 } 54 // ... 55} 56``` 57 58### onWindowStageCreate() 59 60After the [UIAbility](../reference/apis-ability-kit/js-apis-app-ability-uiAbility.md) instance is created but before it becomes visible, the system creates a [WindowStage](../../application-dev/windowmanager/application-window-stage.md) instance and triggers the [onWindowStageCreate()](../reference/apis-ability-kit/js-apis-app-ability-uiAbility.md#onwindowstagecreate) callback. Within this callback, you can load UI content and subscribe to WindowStage events. 61 62In the **onWindowStageCreate()** callback, use [loadContent()](../reference/apis-arkui/arkts-apis-window-Window.md#loadcontent9) to set the page to be loaded, and call [on('windowStageEvent')](../reference/apis-arkui/arkts-apis-window-WindowStage.md#onwindowstageevent9) to subscribe to [WindowStage events](../reference/apis-arkui/arkts-apis-window-e.md#windowstageeventtype9), for example, gaining or losing focus, switching to the foreground or background, or becoming interactive or non-interactive in the foreground. 63 64> **NOTE** 65> 66> - The timing of the [WindowStage events](../reference/apis-arkui/arkts-apis-window-e.md#windowstageeventtype9) may vary according to the development scenario. For details about how to use WindowStage, see [Window Development](../windowmanager/application-window-stage.md). 67> - The UIAbility lifecycle varies with the product type when the main window of an application is switched from the foreground to the background. For details, see [Differentiated Lifecycle Behaviors Across Different Devices](../windowmanager/window-overview.md#differentiated-lifecycle-behaviors-across-different-devices). 68 69```ts 70import { UIAbility } from '@kit.AbilityKit'; 71import { window } from '@kit.ArkUI'; 72import { hilog } from '@kit.PerformanceAnalysisKit'; 73 74const DOMAIN_NUMBER: number = 0xFF00; 75 76export default class EntryAbility extends UIAbility { 77 // ... 78 onWindowStageCreate(windowStage: window.WindowStage): void { 79 // Subscribe to the WindowStage events (gaining or losing focus, switching to the foreground or background, or becoming interactive or non-interactive in the foreground). 80 try { 81 windowStage.on('windowStageEvent', (data) => { 82 let stageEventType: window.WindowStageEventType = data; 83 switch (stageEventType) { 84 case window.WindowStageEventType.SHOWN: // Switch to the foreground. 85 hilog.info(DOMAIN_NUMBER, 'testTag', `windowStage foreground.`); 86 break; 87 case window.WindowStageEventType.ACTIVE: // Gain focus. 88 hilog.info(DOMAIN_NUMBER, 'testTag', `windowStage active.`); 89 break; 90 case window.WindowStageEventType.INACTIVE: // Lose focus. 91 hilog.info(DOMAIN_NUMBER, 'testTag', `windowStage inactive.`); 92 break; 93 case window.WindowStageEventType.HIDDEN: // Switch to the background. 94 hilog.info(DOMAIN_NUMBER, 'testTag', `windowStage background.`); 95 break; 96 case window.WindowStageEventType.RESUMED: // Interactive in the foreground. 97 hilog.info(DOMAIN_NUMBER, 'testTag', `windowStage resumed.`); 98 break; 99 case window.WindowStageEventType.PAUSED: // Non-interactive in the foreground. 100 hilog.info(DOMAIN_NUMBER, 'testTag', `windowStage paused.`); 101 break; 102 default: 103 break; 104 } 105 }); 106 } catch (exception) { 107 hilog.error(DOMAIN_NUMBER, 'testTag', 108 `Failed to enable the listener for window stage event changes. Cause: ${JSON.stringify(exception)}`); 109 } 110 hilog.info(DOMAIN_NUMBER, 'testTag', `%{public}s`, `Ability onWindowStageCreate`); 111 // Set the page to be loaded. 112 windowStage.loadContent('pages/Index', (err, data) => { 113 // ... 114 }); 115 } 116} 117``` 118 119### onForeground() 120 121The system triggers the [onForeground](../reference/apis-ability-kit/js-apis-app-ability-uiAbility.md#onforeground) callback when the [UIAbility](../reference/apis-ability-kit/js-apis-app-ability-uiAbility.md) instance is switching to the foreground and is about to become visible. Within this callback, you can apply for resources required by the system or re-apply for resources that have been released in the **onBackground()** callback. After this callback, the UIAbility instance is fully in the foreground and becomes interactive. The UIAbility instance remains in this state until it is interrupted by some actions (for example, the screen is turned off or the user switches to another UIAbility). 122 123For example, the application has obtained the location permission. Before the UI is displayed, you can enable the location service in the **onForeground()** callback to obtain the location information. 124 125```ts 126import { UIAbility } from '@kit.AbilityKit'; 127 128export default class EntryAbility extends UIAbility { 129 // ... 130 131 onForeground(): void { 132 // Apply for the resources required by the system or re-apply for the resources released in onBackground(). 133 } 134 // ... 135} 136``` 137 138 139### onBackground() 140 141Once the UI of the [UIAbility](../reference/apis-ability-kit/js-apis-app-ability-uiAbility.md) becomes completely invisible, the system triggers the [onBackground](../reference/apis-ability-kit/js-apis-app-ability-uiAbility.md#onbackground) callback and switches the UIAbility instance to the background state. Within this callback, you can release useless resources while the UI is invisible, for example, stopping the location service, to save system resources. 142 143**onBackground()** is executed quickly. Therefore, do not perform time-consuming operations, such as saving user data or executing database transactions, within this callback. 144 145```ts 146import { UIAbility } from '@kit.AbilityKit'; 147 148export default class EntryAbility extends UIAbility { 149 // ... 150 151 onBackground(): void { 152 // Release useless resources while the UI is invisible. 153 } 154 // ... 155} 156``` 157 158 159### onWindowStageWillDestroy() 160The system triggers the [onWindowStageWillDestroy()](../reference/apis-ability-kit/js-apis-app-ability-uiAbility.md#onwindowstagewilldestroy12) callback when the [UIAbility](../reference/apis-ability-kit/js-apis-app-ability-uiAbility.md) instance is about to be destroyed, but still usable. Within this callback, you can release resources obtained through the WindowStage and unsubscribe from WindowStage events. 161 162```ts 163import { UIAbility } from '@kit.AbilityKit'; 164import { window } from '@kit.ArkUI'; 165import { BusinessError } from '@kit.BasicServicesKit'; 166import { hilog } from '@kit.PerformanceAnalysisKit'; 167 168const DOMAIN_NUMBER: number = 0xFF00; 169 170export default class EntryAbility extends UIAbility { 171 windowStage: window.WindowStage | undefined = undefined; 172 // ... 173 onWindowStageCreate(windowStage: window.WindowStage): void { 174 this.windowStage = windowStage; 175 // ... 176 } 177 178 onWindowStageWillDestroy(windowStage: window.WindowStage) { 179 // Release the resources obtained through the windowStage object. 180 // Unsubscribe from the WindowStage events (gaining or losing focus, switching to the foreground or background, or becoming interactive or non-interactive in the foreground) in the onWindowStageWillDestroy() callback. 181 try { 182 if (this.windowStage) { 183 this.windowStage.off('windowStageEvent'); 184 } 185 } catch (err) { 186 let code = (err as BusinessError).code; 187 let message = (err as BusinessError).message; 188 hilog.error(DOMAIN_NUMBER, 'testTag', `Failed to disable the listener for windowStageEvent. Code is ${code}, message is ${message}`); 189 } 190 } 191} 192``` 193 194### onWindowStageDestroy() 195The system triggers the [onWindowStageDestroy()](../reference/apis-ability-kit/js-apis-app-ability-uiAbility.md#onwindowstagedestroy) callback before the [UIAbility](../reference/apis-ability-kit/js-apis-app-ability-uiAbility.md) instance is destroyed, while the WindowStage instance is destroyed and can no longer be used. Within this callback, you can release UI resources. 196 197```ts 198import { UIAbility } from '@kit.AbilityKit'; 199import { window } from '@kit.ArkUI'; 200 201export default class EntryAbility extends UIAbility { 202 // ... 203 204 onWindowStageCreate(windowStage: window.WindowStage): void { 205 // Load UI resources. 206 } 207 208 onWindowStageDestroy() { 209 // Release UI resources. 210 } 211} 212``` 213 214### onDestroy() 215 216The system triggers the [onDestroy](../reference/apis-ability-kit/js-apis-app-ability-uiAbility.md#ondestroy) callback before the [UIAbility](../reference/apis-ability-kit/js-apis-app-ability-uiAbility.md) instance is destroyed. This callback is the last lifecycle callback received by the UIAbility. Within this callback, you can release system resources and save data. 217 218For example, when you call [terminateSelf()](../reference/apis-ability-kit/js-apis-inner-application-uiAbilityContext.md#terminateself) to instruct the system to stop the current UIAbility instance, the system triggers the **onDestroy()** callback. 219<!--RP1-->Similarly, when a user swipes up on the recent tasks list to close a UIAbility instance, the system triggers the **onDestroy()** callback.<!--RP1End--> 220 221```ts 222import { UIAbility } from '@kit.AbilityKit'; 223 224export default class EntryAbility extends UIAbility { 225 // ... 226 227 onDestroy() { 228 // Release system resources and save data. 229 } 230} 231``` 232 233### onNewWant() 234 235The system triggers the [onNewWant()](../reference/apis-ability-kit/js-apis-app-ability-uiAbility.md#onnewwant) callback when an already running UIAbility is launched again. Within this callback, you can update the resources and data to be loaded, which will be used for UI display. 236 237```ts 238import { AbilityConstant, UIAbility, Want } from '@kit.AbilityKit'; 239 240export default class EntryAbility extends UIAbility { 241 // ... 242 243 onNewWant(want: Want, launchParam: AbilityConstant.LaunchParam) { 244 // Update resources and data. 245 } 246} 247``` 248 249<!--no_check--> 250 251 252