• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Context (Stage Model)
2
3
4## Overview
5
6[Context](../reference/apis/js-apis-inner-application-context.md) is the context of an object in an application. It provides basic information about the application, for example, **resourceManager**, **applicationInfo**, **dir** (application development path), and **area** (encrypted area). It also provides basic methods such as **createBundleContext()** and **getApplicationContext()**. The UIAbility component and ExtensionAbility derived class components have their own **Context** classes, for example, the base class **Context**, **ApplicationContext**, **AbilityStageContext**, **UIAbilityContext**, **ExtensionContext**, and **ServiceExtensionContext**.
7
8- The figure below illustrates the inheritance relationship of contexts.
9
10  ![context-inheritance](figures/context-inheritance.png)
11
12- The figure below illustrates the holding relationship of contexts.
13
14  ![context-holding](figures/context-holding.png)
15
16- The following describes the information provided by different contexts.
17  - [UIAbilityContext](../reference/apis/js-apis-inner-application-uiAbilityContext.md): Each UIAbility has the **Context** attribute, which provides APIs to operate the ability, obtain the ability configuration, and more.
18
19     ```ts
20     import UIAbility from '@ohos.app.ability.UIAbility';
21     export default class EntryAbility extends UIAbility {
22         onCreate(want, launchParam) {
23             let uiAbilityContext = this.context;
24             // ...
25         }
26     }
27     ```
28  - Scenario-specific [ExtensionContext](../reference/apis/js-apis-inner-application-extensionContext.md): For example, ServiceExtensionContext, inherited from ExtensionContext, provides APIs related to background services.
29
30     ```ts
31     import ServiceExtensionAbility from '@ohos.app.ability.ServiceExtensionAbility';
32     export default class MyService extends ServiceExtensionAbility {
33         onCreate(want) {
34             let serviceExtensionContext = this.context;
35             // ...
36         }
37     }
38     ```
39  - [AbilityStageContext](../reference/apis/js-apis-inner-application-abilityStageContext.md): module-level context. It provides **HapModuleInfo** and **Configuration** in addition to those provided by the base class **Context**.
40
41     ```ts
42     import AbilityStage from "@ohos.app.ability.AbilityStage";
43     export default class MyAbilityStage extends AbilityStage {
44         onCreate() {
45             let abilityStageContext = this.context;
46             // ...
47         }
48     }
49     ```
50  - [ApplicationContext](../reference/apis/js-apis-inner-application-applicationContext.md): application-level context. It provides APIs for subscribing to ability lifecycle changes, system memory changes, and system environment changes. The application-level context can be obtained from UIAbility, ExtensionAbility, and AbilityStage.
51
52     ```ts
53     import UIAbility from '@ohos.app.ability.UIAbility';
54     export default class EntryAbility extends UIAbility {
55         onCreate(want, launchParam) {
56             let applicationContext = this.context.getApplicationContext();
57             // ...
58         }
59     }
60     ```
61
62
63## Typical Usage Scenarios of Context
64
65
66This topic describes how to use the context in the following scenarios:
67
68
69- [Obtaining the Application Development Path](#obtaining-the-application-development-path)
70- [Obtaining and Modifying Encrypted Areas](#obtaining-and-modifying-encrypted-areas)
71- [Creating Context of Another Application or Module](#creating-context-of-another-application-or-module)
72- [Subscribing to Ability Lifecycle Changes in a Process](#subscribing-to-ability-lifecycle-changes-in-a-process)
73
74
75### Obtaining the Application Development Path
76
77The following table describes the application development paths obtained from context.
78
79**Table 1** Application development paths
80
81| Name| Type| Readable| Writable| Description|
82| -------- | -------- | -------- | -------- | -------- |
83| cacheDir | string | Yes| No| Cache directory of the application on the internal storage.<br>It is the content of **Storage** of an application under **Settings > Apps & services > Apps**.|
84| tempDir | string | Yes| No| Temporary file directory of the application.<br>Files in this directory are deleted after the application is uninstalled.|
85| filesDir | string | Yes| No| File directory of the application on the internal storage.<br>Files in this directory may be synchronized to other directories during application migration or backup.|
86| databaseDir | string | Yes| No| Storage directory of the local database.|
87| bundleCodeDir | string | Yes| No| Installation directory of the application on the internal storage. A resource file cannot be accessed by combining paths. Use [Resource Manager](../reference/apis/js-apis-resource-manager.md) to access it. |
88| distributedFilesDir | string | Yes| No| Storage directory of distributed application data files.|
89| preferencesDir | string | Yes| Yes| Preferences directory of the application.|
90
91The capability of obtaining the application development path is provided by the base class **Context**. This capability is also provided by **ApplicationContext**, **AbilityStageContext**, **UIAbilityContext**, and **ExtensionContext**. However, the paths obtained from different contexts may differ, as shown below.
92
93**Figure 1** Application development paths obtained from context
94
95![context-dir](figures/context-dir.png)
96
97- Obtain the application-level path through **ApplicationContext**. It is recommended that global application information be stored in this path. Files stored in this path will be deleted only when the application is uninstalled.
98    | Name| Path|
99  | -------- | -------- |
100  | bundleCodeDir | {Path prefix}/el1/bundle/|
101  | cacheDir | {Path prefix}/{Encryption level}/base/cache/|
102  | filesDir | {Path prefix}/{Encryption level}/base/files/|
103  | preferencesDir | {Path prefix}/{Encryption level}/base/preferences/|
104  | tempDir | {Path prefix}/{Encryption level}/base/temp/|
105  | databaseDir | {Path prefix}/{Encryption level}/database/|
106  | distributedFilesDir | {Path prefix}/el2/distributedFiles/|
107
108- Obtain the HAP level path through **AbilityStageContext**, **UIAbilityContext**, and **ExtensionContext**. It is recommended that the HAP information be stored in this path. The file content stored in this path will be deleted when the HAP is uninstalled. The file content in the application-level path will be deleted only after all the HAPs of the application are uninstalled.
109    | Name| Path|
110  | -------- | -------- |
111  | bundleCodeDir | {Path prefix}/el1/bundle/|
112  | cacheDir | {Path prefix}/{Encryption level}/base/**haps/{moduleName}**/cache/|
113  | filesDir | {Path prefix}/{Encryption level}/base/**haps/{moduleName}**/files/|
114  | preferencesDir | {path prefix}/{encryption level}/base/**haps/{moduleName}**/preferences/|
115  | tempDir | {Path prefix}/{Encryption level}/base/**haps/{moduleName}**/temp/|
116  | databaseDir | {Path prefix}/{Encryption level}/database/**{moduleName}**/|
117  | distributedFilesDir | {Path prefix}/el2/distributedFiles/**{moduleName}**/|
118
119The sample code for obtaining the application development paths is as follows:
120
121
122```ts
123import UIAbility from '@ohos.app.ability.UIAbility';
124
125export default class EntryAbility extends UIAbility {
126    onCreate(want, launchParam) {
127        let cacheDir = this.context.cacheDir;
128        let tempDir = this.context.tempDir;
129        let filesDir = this.context.filesDir;
130        let databaseDir = this.context.databaseDir;
131        let bundleCodeDir = this.context.bundleCodeDir;
132        let distributedFilesDir = this.context.distributedFilesDir;
133        let preferencesDir = this.context.preferencesDir;
134        // ...
135    }
136}
137```
138
139
140### Obtaining and Modifying Encrypted Areas
141
142You can read and write [the area attribute in the context](../reference/apis/js-apis-inner-application-context.md) to obtain and set an encrypted area. Two encryption levels are supported:
143
144- AreaMode.EL1: device-level encryption area, which is accessible after the device is powered on.
145
146- AreaMode.EL2: user-level encryption area, which is accessible only after the device is powered on and the password is entered (for the first time).
147
148```ts
149import UIAbility from '@ohos.app.ability.UIAbility';
150
151export default class EntryAbility extends UIAbility {
152    onCreate(want, launchParam) {
153        // Before storing common information, switch the encryption level to EL1.
154        if (this.context.area === 1) {// Obtain the area.
155            this.context.area = 0; // Modify the area.
156        }
157        // Store common information.
158
159        // Before storing sensitive information, switch the encryption level to EL2.
160        if (this.context.area === 0) { // Obtain the area.
161            this.context.area = 1;     // Modify the area.
162        }
163        // Store sensitive information.
164    }
165}
166```
167
168
169### Creating Context of Another Application or Module
170
171The base class **Context** provides the [createBundleContext(bundleName:string)](../reference/apis/js-apis-inner-application-context.md#contextcreatebundlecontext), [createModuleContext(moduleName:string)](../reference/apis/js-apis-inner-application-context.md#contextcreatemodulecontext), and [createModuleContext(bundleName:string, moduleName:string)](../reference/apis/js-apis-inner-application-context.md#contextcreatemodulecontext-1) methods for creating the context of other applications or modules, so as to obtain the resource information, for example, [obtaining the application development paths](#obtaining-the-application-development-path) of other modules.
172
173- Call **createBundleContext(bundleName:string)** to create the context of another application.
174  > **NOTE**
175  >
176  > To obtain the context of another application:
177  >
178  > - Request the **ohos.permission.GET_BUNDLE_INFO_PRIVILEGED** permission. For details, see [Permission Application Guide](../security/accesstoken-guidelines.md#declaring-permissions-in-the-configuration-file).
179  >
180  > - This is a system API and cannot be called by third-party applications.
181
182  For example, application information displayed on the home screen includes the application name and icon. The home screen application calls the foregoing method to obtain the context information, so as to obtain the resource information including the application name and icon.
183
184  ```ts
185  import UIAbility from '@ohos.app.ability.UIAbility';
186
187  export default class EntryAbility extends UIAbility {
188      onCreate(want, launchParam) {
189          let bundleName2 = "com.example.application";
190          let context2 = this.context.createBundleContext(bundleName2);
191          let label2 = context2.applicationInfo.label;
192          // ...
193      }
194  }
195  ```
196
197- Call **createModuleContext(bundleName:string, moduleName:string)** to obtain the context of a specified module of another application. After obtaining the context, you can obtain the resource information of that module.
198  > **NOTE**
199  >
200  > To obtain the context of a specified module of another application:
201  >
202  > - Request the **ohos.permission.GET_BUNDLE_INFO_PRIVILEGED** permission. For details, see [Permission Application Guide](../security/accesstoken-guidelines.md#declaring-permissions-in-the-configuration-file).
203  >
204  > - This is a system API and cannot be called by third-party applications.
205
206  ```ts
207  import UIAbility from '@ohos.app.ability.UIAbility';
208
209  export default class EntryAbility extends UIAbility {
210      onCreate(want, launchParam) {
211          let bundleName2 = "com.example.application";
212          let moduleName2 = "module1";
213          let context2 = this.context.createModuleContext(bundleName2, moduleName2);
214          // ...
215      }
216  }
217  ```
218
219- Call **createModuleContext(moduleName:string)** to obtain the context of another module in the current application. After obtaining the context, you can obtain the resource information of that module.
220
221  ```ts
222  import UIAbility from '@ohos.app.ability.UIAbility';
223
224  export default class EntryAbility extends UIAbility {
225      onCreate(want, launchParam) {
226          let moduleName2 = "module1";
227          let context2 = this.context.createModuleContext(moduleName2);
228          // ...
229      }
230  }
231  ```
232
233
234### Subscribing to Ability Lifecycle Changes in a Process
235
236In the DFX statistics scenario of an application, if you need to collect statistics on the stay duration and access frequency of a page, you can subscribe to ability lifecycle changes.
237
238When the ability lifecycle changes in a process, for example, being created or destroyed, becoming visible or invisible, or gaining or losing focus, the corresponding callback is triggered, and a listener ID is returned. The ID is incremented by 1 each time the listener is registered. When the number of listeners exceeds the upper limit (2^63-1), -1 is returned. The following uses [UIAbilityContext](../reference/apis/js-apis-inner-application-uiAbilityContext.md) as an example.
239
240
241```ts
242import UIAbility from '@ohos.app.ability.UIAbility';
243import window from '@ohos.window';
244
245const TAG: string = "[Example].[Entry].[EntryAbility]";
246
247export default class EntryAbility extends UIAbility {
248    lifecycleId: number;
249
250    onCreate(want, launchParam) {
251        let abilityLifecycleCallback = {
252            onAbilityCreate(ability) {
253                console.info(TAG, "onAbilityCreate ability:" + JSON.stringify(ability));
254            },
255            onWindowStageCreate(ability, windowStage) {
256                console.info(TAG, "onWindowStageCreate ability:" + JSON.stringify(ability));
257                console.info(TAG, "onWindowStageCreate windowStage:" + JSON.stringify(windowStage));
258            },
259            onWindowStageActive(ability, windowStage) {
260                console.info(TAG, "onWindowStageActive ability:" + JSON.stringify(ability));
261                console.info(TAG, "onWindowStageActive windowStage:" + JSON.stringify(windowStage));
262            },
263            onWindowStageInactive(ability, windowStage) {
264                console.info(TAG, "onWindowStageInactive ability:" + JSON.stringify(ability));
265                console.info(TAG, "onWindowStageInactive windowStage:" + JSON.stringify(windowStage));
266            },
267            onWindowStageDestroy(ability, windowStage) {
268                console.info(TAG, "onWindowStageDestroy ability:" + JSON.stringify(ability));
269                console.info(TAG, "onWindowStageDestroy windowStage:" + JSON.stringify(windowStage));
270            },
271            onAbilityDestroy(ability) {
272                console.info(TAG, "onAbilityDestroy ability:" + JSON.stringify(ability));
273            },
274            onAbilityForeground(ability) {
275                console.info(TAG, "onAbilityForeground ability:" + JSON.stringify(ability));
276            },
277            onAbilityBackground(ability) {
278                console.info(TAG, "onAbilityBackground ability:" + JSON.stringify(ability));
279            },
280            onAbilityContinue(ability) {
281                console.info(TAG, "onAbilityContinue ability:" + JSON.stringify(ability));
282            }
283        }
284        // 1. Obtain the application context through the context attribute.
285        let applicationContext = this.context.getApplicationContext();
286        // 2. Register a listener for the lifecycle changes through the application context.
287        this.lifecycleId = applicationContext.on("abilityLifecycle", abilityLifecycleCallback);
288        console.info(TAG, "register callback number: " + JSON.stringify(this.lifecycleId));
289    }
290
291    onDestroy() {
292        let applicationContext = this.context.getApplicationContext();
293        applicationContext.off("abilityLifecycle", this.lifecycleId, (error, data) => {
294            console.info(TAG, "unregister callback success, err: " + JSON.stringify(error));
295        });
296    }
297}
298```
299