• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Context (Stage Model)
2
3<!--Kit: Ability Kit-->
4<!--Subsystem: Ability-->
5<!--Owner: @li-weifeng2; @xuzhihao666-->
6<!--Designer: @li-weifeng2-->
7<!--Tester: @lixueqing513-->
8<!--Adviser: @huipeizi-->
9
10## Overview
11
12[Context](../reference/apis-ability-kit/js-apis-inner-application-context.md) serves as the context environment for objects within an application. It provides basic information about the application, for example, [resourceManager](../reference/apis-localization-kit/js-apis-resource-manager.md) (resource management), [applicationInfo](../reference/apis-ability-kit/js-apis-bundleManager-applicationInfo.md) (current application information), and [area](../reference/apis-ability-kit/js-apis-app-ability-contextConstant.md#areamode) (file partitions).
13
14## Comparison of Different Context Types
15
16Both [UIAbility](../reference/apis-ability-kit/js-apis-app-ability-uiAbility.md) components and various derived classes of [ExtensionAbility](../reference/apis-ability-kit/js-apis-app-ability-extensionAbility.md) components have their own context classes. These include the base class Context, [ApplicationContext](../reference/apis-ability-kit/js-apis-inner-application-applicationContext.md), [AbilityStageContext](../reference/apis-ability-kit/js-apis-inner-application-abilityStageContext.md), [UIAbilityContext](../reference/apis-ability-kit/js-apis-inner-application-uiAbilityContext.md), <!--Del-->[ServiceExtensionContext](../reference/apis-ability-kit/js-apis-inner-application-serviceExtensionContext-sys.md), <!--DelEnd-->and [ExtensionContext](../reference/apis-ability-kit/js-apis-inner-application-extensionContext.md). For details about their relationships, see [Inheritance and Holding Relationships of Different Context Types](../reference/apis-ability-kit/js-apis-inner-application-context.md#inheritance-and-holding-relationships-of-different-context-types).
17
18The following table describes how to obtain different types of context and their usage scenarios.
19
20> **NOTE**
21>
22> Different types of context possess distinct capabilities and cannot be substituted for or forcibly converted into one another. For example, [ApplicationContext](../reference/apis-ability-kit/js-apis-inner-application-applicationContext.md) is bound to the [setFontSizeScale](../reference/apis-ability-kit/js-apis-inner-application-applicationContext.md#applicationcontextsetfontsizescale13) API, which is not available in [UIAbilityContext](../reference/apis-ability-kit/js-apis-inner-application-uiAbilityContext.md). Therefore, even if you forcibly convert UIAbilityContext to ApplicationContext, you will not be able to call the **setFontSizeScale** API.
23
24**Table 1** Different context types
25
26| Context Type| Description| Acquisition Method| Usage Scenario|
27| -------- | -------- | -------- | -------- |
28| [ApplicationContext](../reference/apis-ability-kit/js-apis-inner-application-applicationContext.md) | Global context of an application, providing application-level information and capabilities.| - From API version 14 onwards, you can directly call [getApplicationContext](../reference/apis-ability-kit/js-apis-app-ability-application.md#applicationgetapplicationcontext14) to obtain it.<br>- In versions earlier than API version 14, you can obtain it by calling [getApplicationContext](../reference/apis-ability-kit/js-apis-inner-application-context.md#getapplicationcontext) of a Context instance.| - [Obtain basic information about the current application](#obtaining-basic-information).<br>- [Obtain application file paths](#obtaining-application-file-paths).<br>- [Obtain and modifying encryption levels](#obtaining-and-modifying-encryption-levels).<br>- [Register a listener for application foreground/background changes](#listening-for-application-foregroundbackground-changes).|
29| [AbilityStageContext](../reference/apis-ability-kit/js-apis-inner-application-abilityStageContext.md) | Context of a module, providing module-level information and capabilities.| - To obtain the context of the current AbilityStage, you can directly access the [context](../reference/apis-ability-kit/js-apis-app-ability-abilityStage.md#properties) property of the AbilityStage instance.<br> - To obtain the context of another module in the same application, you can call [createModuleContext](../reference/apis-ability-kit/js-apis-app-ability-application.md#applicationcreatemodulecontext12).| - Obtain basic information about the current module.<br>- [Obtain module file paths](#obtaining-application-file-paths).|
30| [UIAbilityContext](../reference/apis-ability-kit/js-apis-inner-application-uiAbilityContext.md) | Context of a UIAbility, providing external information and capabilities of the UIAbility.| - You can directly access the [context](../reference/apis-ability-kit/js-apis-app-ability-uiAbility.md#properties) property through a UIAbility instance.<br>- To load a UI component instance in the window of a UIAbility, call [getHostContext](../reference/apis-arkui/arkts-apis-uicontext-uicontext.md#gethostcontext12) of the UIContext.| - Obtain basic information about the current UIAbility.<br>- Start other applications or atomic services, and connect to or disconnect from ServiceExtensionAbility components created by system applications.<br>- Destroy the current UIAbility.|
31| [ExtensionContext](../reference/apis-ability-kit/js-apis-inner-application-extensionContext.md) | Context of an ExtensionAbility. Each type of ExtensionContext provides different information and capabilities.| Directly access the context property through an ExtensionAbility instance.| The capabilities provided by the context corresponding to different types of ExtensionAbility vary. For example, [InputMethodExtensionContext](../reference/apis-ime-kit/js-apis-inputmethod-extension-context.md) mainly provides the following capabilities:<br>- Obtain the basic information about the InputMethodExtensionAbility.<br>- Destroy the current input method.|
32| [UIContext](../reference/apis-arkui/arkts-apis-uicontext-uicontext.md) | Context of a UI instance of ArkUI, providing capabilities related to UI operations. It is not directly related to the other types of context mentioned above.| - To obtain the UI context within a UI component, directly call [getHostContext](../reference/apis-arkui/arkts-apis-uicontext-uicontext.md#gethostcontext12).<br>- If a Window instance exists, call [getUIContext](../reference/apis-arkui/arkts-apis-window-Window.md#getuicontext10) provided by the Window instance.| Use it for UI-related operations in the UI instance, for example:<br>- Obtain the font of the current UI instance.<br>- Display different types of dialog boxes.<br>- Set the UI avoid mode when the soft keyboard is displayed.|
33
34## Acquisition of Context
35
36If you need to obtain application resources, application paths, or use the methods provided by Context to implement operations such as application redirection, environment variable setting, data clearing, and permission obtaining, you need to obtain the corresponding context. This section describes how to obtain different types of context and where to use it.
37
38### Obtaining ApplicationContext (Global Application Context)
39
40[ApplicationContext](../reference/apis-ability-kit/js-apis-inner-application-applicationContext.md) provides capabilities such as listening for lifecycle changes of application components within the application, system memory changes, system environment changes, setting application language, setting application color mode, clearing application data, and revoking permissions granted by the user. It can be obtained in [UIAbility](../reference/apis-ability-kit/js-apis-app-ability-uiAbility.md), [ExtensionAbility](../reference/apis-ability-kit/js-apis-app-ability-extensionAbility.md), and [AbilityStage](../reference/apis-ability-kit/js-apis-app-ability-abilityStage.md).
41
42  ```ts
43  import { UIAbility, AbilityConstant, Want } from '@kit.AbilityKit';
44
45  export default class EntryAbility extends UIAbility {
46    onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void {
47      let applicationContext = this.context.getApplicationContext();
48      //...
49    }
50  }
51  ```
52
53### Obtains AbilityStageContext (Module-Level Context)
54
55Compared with the base class Context, [AbilityStageContext](../reference/apis-ability-kit/js-apis-inner-application-abilityStageContext.md) additionally provides information such as [HapModuleInfo](../reference/apis-ability-kit/js-apis-bundleManager-hapModuleInfo.md) and [Configuration](../reference/apis-ability-kit/js-apis-app-ability-configuration.md).
56
57  ```ts
58  import { AbilityStage } from '@kit.AbilityKit';
59
60  export default class MyAbilityStage extends AbilityStage {
61    onCreate(): void {
62      let abilityStageContext = this.context;
63      //...
64    }
65  }
66  ```
67
68### Obtaining Context of Another Module in the Current Application (Module-Level Context)
69
70Call [createModuleContext](../reference/apis-ability-kit/js-apis-app-ability-application.md#applicationcreatemodulecontext12) to obtain the context of another module in the current application. After obtaining the context, you can obtain the resource information of that module.
71
72  ```ts
73  import { common, application } from '@kit.AbilityKit';
74  import { BusinessError } from '@kit.BasicServicesKit';
75
76  let storageEventCall = new LocalStorage();
77
78  @Entry(storageEventCall)
79  @Component
80  struct Page_Context {
81    private context = this.getUIContext().getHostContext() as common.UIAbilityContext;
82
83    build() {
84      Column() {
85        //...
86        List({ initialIndex: 0 }) {
87          ListItem() {
88            Row() {
89              //...
90            }
91            .onClick(() => {
92              let moduleName2: string = 'entry';
93              application.createModuleContext(this.context, moduleName2)
94                .then((data: common.Context) => {
95                  console.info(`CreateModuleContext success, data: ${JSON.stringify(data)}`);
96                  if (data !== null) {
97                    this.getUIContext().getPromptAction().showToast({
98                      message: ('Context obtained')
99                    });
100                  }
101                })
102                .catch((err: BusinessError) => {
103                  console.error(`CreateModuleContext failed, err code:${err.code}, err msg: ${err.message}`);
104                });
105            })
106          }
107          //...
108        }
109        //...
110      }
111      //...
112    }
113  }
114  ```
115
116### Obtaining UIAbilityContext (Context Corresponding to the UIAbility)
117
118The [UIAbility](../reference/apis-ability-kit/js-apis-app-ability-uiAbility.md) class has its own context, which is an instance of the [UIAbilityContext](../reference/apis-ability-kit/js-apis-inner-application-uiAbilityContext.md) class. The [UIAbilityContext](../reference/apis-ability-kit/js-apis-inner-application-uiAbilityContext.md) class has attributes such as **abilityInfo** and **currentHapModuleInfo**. UIAbilityContext can be used to obtain the UIAbility configuration information, such as the code path, bundle name, ability name, and environment status required by the application. It can also be used to obtain methods to operate the UIAbility instance, such as [startAbility()](../reference/apis-ability-kit/js-apis-inner-application-uiAbilityContext.md#startability), [connectServiceExtensionAbility()](../reference/apis-ability-kit/js-apis-inner-application-uiAbilityContext.md#connectserviceextensionability), and [terminateSelf()](../reference/apis-ability-kit/js-apis-inner-application-uiAbilityContext.md#terminateself).
119
120If you need to obtain the context of the current ability in the page, you can call [getHostContext](../reference/apis-arkui/arkts-apis-uicontext-uicontext.md#gethostcontext12) in [UIContext](../reference/apis-arkui/arkts-apis-uicontext-uicontext.md) to obtain the UIAbilityContext or [ExtensionContext](../reference/apis-ability-kit/js-apis-inner-application-extensionContext.md) associated with the current page.
121
122- You can use **this.context** to obtain the context of a UIAbility instance.
123
124  ```ts
125  import { UIAbility, AbilityConstant, Want } from '@kit.AbilityKit';
126
127  export default class EntryAbility extends UIAbility {
128    onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void {
129      // Obtain the context of the UIAbility instance.
130      let context = this.context;
131      // ...
132    }
133  }
134  ```
135
136- Import the context module and define the **context** variable in the component.
137
138  ```ts
139  import { common, Want } from '@kit.AbilityKit';
140
141  @Entry
142  @Component
143  struct Page_EventHub {
144    private context = this.getUIContext().getHostContext() as common.UIAbilityContext;
145
146    startAbilityTest(): void {
147      let want: Want = {
148        // Want parameter information.
149      };
150      this.context.startAbility(want);
151    }
152
153    // UI page display.
154    build() {
155      // ...
156    }
157  }
158  ```
159
160  You can also define variables after importing the context module but before using [UIAbilityContext](../reference/apis-ability-kit/js-apis-inner-application-uiAbilityContext.md).
161
162
163  ```ts
164  import { common, Want } from '@kit.AbilityKit';
165
166  @Entry
167  @Component
168  struct Page_UIAbilityComponentsBasicUsage {
169    startAbilityTest(): void {
170      let context = this.getUIContext().getHostContext() as common.UIAbilityContext;
171      let want: Want = {
172        // Want parameter information.
173      };
174      context.startAbility(want);
175    }
176
177    // UI page display.
178    build() {
179      // ...
180    }
181  }
182  ```
183
184- To stop the [UIAbility](../reference/apis-ability-kit/js-apis-app-ability-uiAbility.md) instance after the service is not needed, call [terminateSelf()](../reference/apis-ability-kit/js-apis-inner-application-uiAbilityContext.md#terminateself).
185
186  ```ts
187  import { common } from '@kit.AbilityKit';
188  import { BusinessError } from '@kit.BasicServicesKit';
189
190  @Entry
191  @Component
192  struct Page_UIAbilityComponentsBasicUsage {
193    // UI page display.
194    build() {
195      Column() {
196        //...
197        Button('FuncAbilityB')
198          .onClick(() => {
199            let context = this.getUIContext().getHostContext() as common.UIAbilityContext;
200            try {
201              context.terminateSelf((err: BusinessError) => {
202                if (err.code) {
203                  // Process service logic errors.
204                  console.error(`terminateSelf failed, code is ${err.code}, message is ${err.message}.`);
205                  return;
206                }
207                // Carry out normal service processing.
208                console.info(`terminateSelf succeed.`);
209              });
210            } catch (err) {
211              // Capture the synchronization parameter error.
212              let code = (err as BusinessError).code;
213              let message = (err as BusinessError).message;
214              console.error(`terminateSelf failed, code is ${code}, message is ${message}.`);
215            }
216          })
217      }
218    }
219  }
220  ```
221
222### Obtaining ExtensionAbilityContext (Component-Level Context)
223
224Obtain a scenario-specific [ExtensionContext](../reference/apis-ability-kit/js-apis-inner-application-extensionContext.md). For example, FormExtensionContext, which inherits from ExtensionContext, provides APIs related to widget services.
225
226```ts
227import { FormExtensionAbility, formBindingData } from '@kit.FormKit';
228import { Want } from '@kit.AbilityKit';
229
230export default class MyFormExtensionAbility extends FormExtensionAbility {
231  onAddForm(want: Want) {
232    let formExtensionContext = this.context;
233    // ...
234    let dataObj1: Record<string, string> = {
235      'temperature': '11c',
236      'time': '11:00'
237    };
238    let obj1: formBindingData.FormBindingData = formBindingData.createFormBindingData(dataObj1);
239    return obj1;
240  }
241}
242```
243
244
245## Typical Usage Scenarios of Context
246
247
248This topic describes how to use the context in the following scenarios:
249
250- [Obtaining Basic Information](#obtaining-basic-information)
251- [Obtaining Application File Paths](#obtaining-application-file-paths)
252- [Obtaining and Modifying Encryption Levels](#obtaining-and-modifying-encryption-levels)
253- [Listening for Application Foreground/Background Changes](#listening-for-application-foregroundbackground-changes)
254- [Listening for UIAbility Lifecycle Changes](#listening-for-uiability-lifecycle-changes)
255
256### Obtaining Basic Information
257
258Different types of Context classes, which inherit from [Context](../reference/apis-ability-kit/js-apis-inner-application-context.md), default to inheriting the parent class's methods and properties, as well as having their own independent methods and properties.
259
260You can obtain basic information about the current application, module, UIAbility, or ExtensionAbility through the context property (such as the resource manager object and application information). Below is an example of acquiring information for the UIAbility.
261
262If you need to obtain resource objects across packages, see [Accessing Resources](../quick-start/resource-categories-and-access.md#accessing-resources).
263
264  ```ts
265  import { UIAbility, AbilityConstant, Want } from '@kit.AbilityKit';
266
267  export default class EntryAbility extends UIAbility {
268    onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void {
269      // Obtain a resource manager.
270      let resourceManager = this.context.getApplicationContext().resourceManager;
271      // Obtain application information.
272      let applicationInfo = this.context.getApplicationContext().applicationInfo;
273      //...
274    }
275  }
276  ```
277
278### Obtaining Application File Paths
279
280The [base class Context](../reference/apis-ability-kit/js-apis-inner-application-context.md) provides the capability of obtaining application file paths. [ApplicationContext](../reference/apis-ability-kit/js-apis-inner-application-applicationContext.md), [AbilityStageContext](../reference/apis-ability-kit/js-apis-inner-application-abilityStageContext.md), [UIAbilityContext](../reference/apis-ability-kit/js-apis-inner-application-uiAbilityContext.md), and [ExtensionContext](../reference/apis-ability-kit/js-apis-inner-application-extensionContext.md) inherit this capability. However, the specific paths retrieved can differ based on the type of the context used.
281
282- [ApplicationContext](../reference/apis-ability-kit/js-apis-inner-application-applicationContext.md): This context provides access to the application-level file path, which is used to store global application information. Files in this path are removed when the application is uninstalled.
283- [AbilityStageContext](../reference/apis-ability-kit/js-apis-inner-application-abilityStageContext.md), [UIAbilityContext](../reference/apis-ability-kit/js-apis-inner-application-uiAbilityContext.md), and [ExtensionContext](../reference/apis-ability-kit/js-apis-inner-application-extensionContext.md): These contexts provide access to [module-level](../quick-start/application-package-overview.md) file paths. Files in these paths are removed when the corresponding [HAP](../quick-start/hap-package.md) or [HSP](../quick-start/in-app-hsp.md) module is uninstalled. Uninstalling an HAP or HSP module does not affect files under the application-level path unless all HAP and HSP modules of the application are uninstalled.
284
285  - UIAbilityContext: This context can be used to obtain the file paths of the module containing the UIAbility.
286  - ExtensionContext: This context can be used to obtain the file paths of the module containing the ExtensionAbility.
287  - AbilityStageContext: Given that AbilityStageContext is initialized earlier than UIAbilityContext and ExtensionContext, it is typically used to obtain file paths within the AbilityStage.
288
289>**NOTE**
290>
291> The application file paths are a type of application sandbox paths. For details, see [Application Sandbox Directory](../file-management/app-sandbox-directory.md).
292
293  **Table 1** Description of application file paths obtained by different types of contexts
294| Name| Description| Path Obtained by ApplicationContext| Path Obtained by AbilityStageContext, UIAbilityContext, and ExtensionContext|
295| -------- | -------- | -------- | -------- |
296| bundleCodeDir | Bundle code directory.| \<Path prefix>/el1/bundle| \<Path prefix>/el1/bundle|
297| cacheDir | Cache directory.| \<Path prefix>/\<Encryption level>/base/cache| \<Path prefix>/\<Encryption level>/base/**haps/\<module-name>**/cache|
298| filesDir | File directory.| \<Path prefix>/\<Encryption level>/base/files| \<Path prefix>/\<Encryption level>/base/**haps/\<module-name>**/files|
299| preferencesDir | Preferences directory.| \<Path prefix>/\<Encryption level>/base/preferences| \<Path prefix>/\<Encryption level>/base/**haps/\<module-name>**/preferences|
300| tempDir | Temporary directory.| \<Path prefix>/\<Encryption level>/base/temp| \<Path prefix>/\<Encryption level>/base/**haps/\<module-name>**/temp|
301| databaseDir | Database directory.| \<Path prefix>/\<Encryption level>/database| \<Path prefix>/\<Encryption level>/database/**\<module-name>**|
302| distributedFilesDir | Distributed file directory.| \<Path prefix>/el2/distributedFiles| \<Path prefix>/el2/distributedFiles/|
303| resourceDir<sup>11+<sup> | Resource directory.<br>**NOTE**<br> You are required to manually create the **resfile** directory in **\<module-name>\resource**.| N/A| \<Path prefix>/el1/bundle/**\<module-name>**/resources/resfile|
304| cloudFileDir<sup>12+</sup> | Cloud file directory.| \<Path prefix>/el2/cloud| \<Path prefix>/el2/cloud/|
305
306This section uses ApplicationContext to obtain **cacheDir** and **filesDir** as an example to describe how to obtain the application cache directory and application file directory, and how to use these paths to create and read/write files.
307
308- **Obtaining the Application Cache Directory**
309
310  ```ts
311  import { common } from '@kit.AbilityKit';
312
313  const TAG: string = '[Page_Context]';
314  const DOMAIN_NUMBER: number = 0xFF00;
315
316  @Entry
317  @Component
318  struct Index {
319    @State message: string = 'Hello World';
320    private context = this.getUIContext().getHostContext() as common.UIAbilityContext;
321
322    build() {
323      Row() {
324        Column() {
325          Text(this.message)
326          // ...
327          Button() {
328            Text('create file')
329              // ...
330              .onClick(() => {
331                let applicationContext = this.context.getApplicationContext();
332                // Obtain the application cache directory.
333                let cacheDir = applicationContext.cacheDir;
334              })
335          }
336          // ...
337        }
338        // ...
339      }
340      // ...
341    }
342  }
343  ```
344
345- **Obtaining the Application File Directory**
346
347  ```ts
348  import { common } from '@kit.AbilityKit';
349  import { buffer } from '@kit.ArkTS';
350  import { fileIo, ReadOptions } from '@kit.CoreFileKit';
351  import { hilog } from '@kit.PerformanceAnalysisKit';
352
353  const TAG: string = '[Page_Context]';
354  const DOMAIN_NUMBER: number = 0xFF00;
355
356  @Entry
357  @Component
358  struct Index {
359    @State message: string = 'Hello World';
360    private context = this.getUIContext().getHostContext() as common.UIAbilityContext;
361
362    build() {
363      Row() {
364        Column() {
365          Text(this.message)
366          // ...
367          Button() {
368            Text('create file')
369              // ...
370              .onClick(() => {
371                let applicationContext = this.context.getApplicationContext();
372                // Obtain the application file path.
373                let filesDir = applicationContext.filesDir;
374                hilog.info(DOMAIN_NUMBER, TAG, `filePath: ${filesDir}`);
375                // Create and open the file if it does not exist. Open the file if it already exists.
376                let file = fileIo.openSync(filesDir + '/test.txt', fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE);
377                // Write data to the file.
378                let writeLen = fileIo.writeSync(file.fd, "Try to write str.");
379                hilog.info(DOMAIN_NUMBER, TAG, `The length of str is: ${writeLen}`);
380                // Create an ArrayBuffer object with a size of 1024 bytes to store the data read from the file.
381                let arrayBuffer = new ArrayBuffer(1024);
382                // Set the offset and length to read.
383                let readOptions: ReadOptions = {
384                  offset: 0,
385                  length: arrayBuffer.byteLength
386                };
387                // Read the file content to the ArrayBuffer object and return the number of bytes that are actually read.
388                let readLen = fileIo.readSync(file.fd, arrayBuffer, readOptions);
389                // Convert the ArrayBuffer object into a Buffer object and output it as a string.
390                let buf = buffer.from(arrayBuffer, 0, readLen);
391                hilog.info(DOMAIN_NUMBER, TAG, `the content of file: ${buf.toString()}`);
392                // Close the file.
393                fileIo.closeSync(file);
394              })
395          }
396          // ...
397        }
398        // ...
399      }
400      // ...
401    }
402  }
403  ```
404
405### Obtaining and Modifying Encryption Levels
406
407Encrypting application files enhances data security by preventing files from unauthorized access. Different application files require different levels of protection.
408
409In practice, you need to select a proper encryption level based on scenario-specific requirements to protect application data security. The proper use of EL1 and the EL2 can efficiently improve the security. For details about the permissions required for a specific encryption level, see [AreaMode](../reference/apis-ability-kit/js-apis-app-ability-contextConstant.md#areamode) in [ContextConstant](../reference/apis-ability-kit/js-apis-app-ability-contextConstant.md).
410
411- EL1: For private files, such as alarms and wallpapers, the application can place them in a directory with the device-level encryption (EL1) to ensure that they can be accessed before the user enters the password.
412- EL2: For sensitive files, such as personal privacy data, the application can place them in a directory with the user-level encryption (EL2).
413- EL3: For step recording, file download, or music playback that needs to read, write, and create files when the screen is locked, the application can place these files in EL3.
414- EL4: For files that are related to user security information and do not need to be read, written, or created when the screen is locked, the application can place them in EL4.
415- EL5: By default, sensitive user privacy files cannot be read or written on the lock screen. If such files need to be read or written on the lock screen, you can call [acquireAccess](../reference/apis-ability-kit/js-apis-screenLockFileManager.md#screenlockfilemanageracquireaccess) to apply for reading or writing files before the screen is locked or create new files that can be read and written after the screen is locked. It is more appropriate to place these files in EL5.
416
417You can obtain and set the encryption level by reading and writing the **area** attribute in [Context](../reference/apis-ability-kit/js-apis-inner-application-context.md).
418
419```ts
420// EntryAbility.ets
421import { UIAbility, contextConstant, AbilityConstant, Want } from '@kit.AbilityKit';
422
423export default class EntryAbility extends UIAbility {
424  onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) {
425    // Before storing common information, switch the encryption level to EL1.
426    this.context.area = contextConstant.AreaMode.EL1; // Change the encryption level.
427    // Store common information.
428
429    // Before storing sensitive information, switch the encryption level to EL2.
430    this.context.area = contextConstant.AreaMode.EL2; // Change the encryption level.
431    // Store sensitive information.
432
433    // Before storing sensitive information, switch the encryption level to EL3.
434    this.context.area = contextConstant.AreaMode.EL3; // Change the encryption level.
435    // Store sensitive information.
436
437    // Before storing sensitive information, switch the encryption level to EL4.
438    this.context.area = contextConstant.AreaMode.EL4; // Change the encryption level.
439    // Store sensitive information.
440
441    // Before storing sensitive information, switch the encryption level to EL5.
442    this.context.area = contextConstant.AreaMode.EL5; // Change the encryption level.
443    // Store sensitive information.
444  }
445}
446```
447```ts
448// Index.ets
449import { contextConstant, common } from '@kit.AbilityKit';
450
451@Entry
452@Component
453struct Page_Context {
454  private context = this.getUIContext().getHostContext() as common.UIAbilityContext;
455
456  build() {
457    Column() {
458      //...
459      List({ initialIndex: 0 }) {
460        //...
461        ListItem() {
462          Row() {
463            //...
464          }
465          .onClick(() => {
466            // Before storing common information, switch the encryption level to EL1.
467            if (this.context.area === contextConstant.AreaMode.EL2) { // Obtain the encryption level.
468              this.context.area = contextConstant.AreaMode.EL1; // Change the encryption level.
469              this.getUIContext().getPromptAction().showToast({
470                message: 'SwitchToEL1'
471              });
472            }
473            // Store common information.
474          })
475        }
476        //...
477        ListItem() {
478          Row() {
479            //...
480          }
481          .onClick(() => {
482            // Before storing sensitive information, switch the encryption level to EL2.
483            if (this.context.area === contextConstant.AreaMode.EL1) { // Obtain the encryption level.
484              this.context.area = contextConstant.AreaMode.EL2; // Change the encryption level.
485              this.getUIContext().getPromptAction().showToast({
486                message: 'SwitchToEL2'
487              });
488            }
489            // Store sensitive information.
490          })
491        }
492        //...
493      }
494      //...
495    }
496    //...
497  }
498}
499```
500
501### Listening for Application Foreground/Background Changes
502
503You can use the capabilities of [ApplicationContext](../reference/apis-ability-kit/js-apis-inner-application-applicationContext.md) to listen for changes in the application's foreground and background state. When the application switches between foreground and background, corresponding callback functions can be triggered to execute methods that depend on the foreground/background state or to collect data on the frequency of application state changes.
504
505The following uses [UIAbilityContext](../reference/apis-ability-kit/js-apis-inner-application-uiAbilityContext.md) as an example.
506
507```ts
508import { UIAbility, ApplicationStateChangeCallback } from '@kit.AbilityKit';
509import { BusinessError } from '@kit.BasicServicesKit';
510
511export default class LifecycleAbility extends UIAbility {
512  onCreate() {
513    let applicationStateChangeCallback: ApplicationStateChangeCallback = {
514      onApplicationForeground() {
515        console.info('applicationStateChangeCallback onApplicationForeground');
516      },
517      onApplicationBackground() {
518        console.info('applicationStateChangeCallback onApplicationBackground');
519      }
520    }
521
522    // 1. Obtain an applicationContext object.
523    let applicationContext = this.context.getApplicationContext();
524    try {
525      // 2. Use applicationContext.on() to subscribe to the 'applicationStateChange' event.
526      applicationContext.on('applicationStateChange', applicationStateChangeCallback);
527    } catch (paramError) {
528      console.error(`error: ${(paramError as BusinessError).code}, ${(paramError as BusinessError).message}`);
529    }
530    console.log('Register applicationStateChangeCallback');
531  }
532}
533```
534
535### Listening for UIAbility Lifecycle Changes
536
537You can use [ApplicationContext](../reference/apis-ability-kit/js-apis-inner-application-applicationContext.md) to listen for lifecycle changes of a UIAbility. When the lifecycle of a [UIAbility](../reference/apis-ability-kit/js-apis-app-ability-uiAbility.md) changes, for example, a UIAbility is created, brought to the foreground, sent to the background, or destroyed, corresponding callback functions are invoked. In this way, the methods that depend on the UIAbility lifecycle can be executed, and the dwell time and access frequency of a specified page can be collected.
538
539Each time the callback is registered, a listener lifecycle ID is returned, with the value incremented by 1 each time. When the number of listeners exceeds the upper limit (2^63-1), **-1** is returned. The following uses [UIAbilityContext](../reference/apis-ability-kit/js-apis-inner-application-uiAbilityContext.md) as an example.
540
541```ts
542import { AbilityConstant, AbilityLifecycleCallback, UIAbility, Want } from '@kit.AbilityKit';
543import { hilog } from '@kit.PerformanceAnalysisKit';
544import { window } from '@kit.ArkUI';
545import  { BusinessError } from '@kit.BasicServicesKit';
546
547const TAG: string = '[LifecycleAbility]';
548const DOMAIN_NUMBER: number = 0xFF00;
549
550export default class LifecycleAbility extends UIAbility {
551  // Define a lifecycle ID.
552  lifecycleId: number = -1;
553
554  onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void {
555    // Define a lifecycle callback object.
556    let abilityLifecycleCallback: AbilityLifecycleCallback = {
557      // Called when a UIAbility is created.
558      onAbilityCreate(uiAbility) {
559        hilog.info(DOMAIN_NUMBER, TAG, `onAbilityCreate uiAbility.launchWant: ${JSON.stringify(uiAbility.launchWant)}`);
560      },
561      // Called when a window is created.
562      onWindowStageCreate(uiAbility, windowStage: window.WindowStage) {
563        hilog.info(DOMAIN_NUMBER, TAG, `onWindowStageCreate uiAbility.launchWant: ${JSON.stringify(uiAbility.launchWant)}`);
564        hilog.info(DOMAIN_NUMBER, TAG, `onWindowStageCreate windowStage: ${JSON.stringify(windowStage)}`);
565      },
566      // Called when the window becomes active.
567      onWindowStageActive(uiAbility, windowStage: window.WindowStage) {
568        hilog.info(DOMAIN_NUMBER, TAG, `onWindowStageActive uiAbility.launchWant: ${JSON.stringify(uiAbility.launchWant)}`);
569        hilog.info(DOMAIN_NUMBER, TAG, `onWindowStageActive windowStage: ${JSON.stringify(windowStage)}`);
570      },
571      // Called when the window becomes inactive.
572      onWindowStageInactive(uiAbility, windowStage: window.WindowStage) {
573        hilog.info(DOMAIN_NUMBER, TAG, `onWindowStageInactive uiAbility.launchWant: ${JSON.stringify(uiAbility.launchWant)}`);
574        hilog.info(DOMAIN_NUMBER, TAG, `onWindowStageInactive windowStage: ${JSON.stringify(windowStage)}`);
575      },
576      // Called when the window is destroyed.
577      onWindowStageDestroy(uiAbility, windowStage: window.WindowStage) {
578        hilog.info(DOMAIN_NUMBER, TAG, `onWindowStageDestroy uiAbility.launchWant: ${JSON.stringify(uiAbility.launchWant)}`);
579        hilog.info(DOMAIN_NUMBER, TAG, `onWindowStageDestroy windowStage: ${JSON.stringify(windowStage)}`);
580      },
581      // Called when the UIAbility is destroyed.
582      onAbilityDestroy(uiAbility) {
583        hilog.info(DOMAIN_NUMBER, TAG, `onAbilityDestroy uiAbility.launchWant: ${JSON.stringify(uiAbility.launchWant)}`);
584      },
585      // Called when the UIAbility is switched from the background to the foreground.
586      onAbilityForeground(uiAbility) {
587        hilog.info(DOMAIN_NUMBER, TAG, `onAbilityForeground uiAbility.launchWant: ${JSON.stringify(uiAbility.launchWant)}`);
588      },
589      // Called when the UIAbility is switched from the foreground to the background.
590      onAbilityBackground(uiAbility) {
591        hilog.info(DOMAIN_NUMBER, TAG, `onAbilityBackground uiAbility.launchWant: ${JSON.stringify(uiAbility.launchWant)}`);
592      },
593      // Called when UIAbility is continued on another device.
594      onAbilityContinue(uiAbility) {
595        hilog.info(DOMAIN_NUMBER, TAG, `onAbilityContinue uiAbility.launchWant: ${JSON.stringify(uiAbility.launchWant)}`);
596      }
597    };
598    // Obtain the application context.
599    let applicationContext = this.context.getApplicationContext();
600    try {
601      // Register the application lifecycle callback.
602      this.lifecycleId = applicationContext.on('abilityLifecycle', abilityLifecycleCallback);
603    } catch (err) {
604      let code = (err as BusinessError).code;
605      let message = (err as BusinessError).message;
606      hilog.error(DOMAIN_NUMBER, TAG, `Failed to register applicationContext. Code is ${code}, message is ${message}`);
607    }
608
609    hilog.info(DOMAIN_NUMBER, TAG, `register callback number: ${this.lifecycleId}`);
610  }
611  //...
612  onDestroy(): void {
613    // Obtain the application context.
614    let applicationContext = this.context.getApplicationContext();
615    try {
616      // Deregister the application lifecycle callback.
617      applicationContext.off('abilityLifecycle', this.lifecycleId);
618    } catch (err) {
619      let code = (err as BusinessError).code;
620      let message = (err as BusinessError).message;
621      hilog.error(DOMAIN_NUMBER, TAG, `Failed to unregister applicationContext. Code is ${code}, message is ${message}`);
622    }
623  }
624}
625```
626
627<!--no_check-->