• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Context (Stage Model)
2
3## Overview
4
5[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 level). 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**.
6
7- The figure below illustrates the inheritance relationship of contexts.
8  ![context-inheritance](figures/context-inheritance.png)
9
10- The figure below illustrates the holding relationship of contexts.
11  ![context-holding](figures/context-holding.png)
12
13The following describes the information provided by different contexts.
14  - [UIAbilityContext](../reference/apis/js-apis-inner-application-uiAbilityContext.md): Each UIAbility has the **Context** attribute, which provides APIs to operate an application component, obtain the application component configuration, and more.
15
16     ```ts
17     import UIAbility from '@ohos.app.ability.UIAbility';
18     export default class EntryAbility extends UIAbility {
19       onCreate(want, launchParam) {
20         let uiAbilityContext = this.context;
21         ...
22       }
23     }
24     ```
25
26     > **NOTE**
27     >
28     > For details about how to obtain the context of a **UIAbility** instance on the page, see [Obtaining the Context of UIAbility](uiability-usage.md#obtaining-the-context-of-uiability).
29  - Scenario-specific [ExtensionContext](../reference/apis/js-apis-inner-application-extensionContext.md): For example, ServiceExtensionContext, inherited from ExtensionContext, provides APIs related to background services.
30
31     ```ts
32     import ServiceExtensionAbility from '@ohos.app.ability.ServiceExtensionAbility';
33     export default class MyService extends ServiceExtensionAbility {
34       onCreate(want) {
35         let serviceExtensionContext = this.context;
36         ...
37       }
38     }
39     ```
40  - [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**.
41
42     ```ts
43     import AbilityStage from '@ohos.app.ability.AbilityStage';
44     export default class MyAbilityStage extends AbilityStage {
45       onCreate() {
46         let abilityStageContext = this.context;
47         ...
48       }
49     }
50     ```
51  - [ApplicationContext](../reference/apis/js-apis-inner-application-applicationContext.md): application-level context. It provides APIs for subscribing to application component lifecycle changes, system memory changes, and system environment changes. The application-level context can be obtained from UIAbility, ExtensionAbility, and AbilityStage.
52
53     ```ts
54     import UIAbility from '@ohos.app.ability.UIAbility';
55     export default class EntryAbility extends UIAbility {
56       onCreate(want, launchParam) {
57         let applicationContext = this.context.getApplicationContext();
58         ...
59       }
60     }
61     ```
62
63
64## Typical Usage Scenarios of Context
65
66
67This topic describes how to use the context in the following scenarios:
68
69
70- [Obtaining the Application Development Path](#obtaining-the-application-development-path)
71- [Obtaining and Modifying Encryption Levels](#obtaining-and-modifying-encryption-levels)
72- [Creating Context of Another Application or Module](#creating-context-of-another-application-or-module)
73- [Subscribing to UIAbility Lifecycle Changes in a Process](#subscribing-to-uiability-lifecycle-changes-in-a-process)
74
75
76### Obtaining the Application Development Path
77
78The following table describes the application development paths obtained from context.
79
80**Table 1** Application development paths
81
82| Name| Type| Readable| Writable| Description|
83| -------- | -------- | -------- | -------- | -------- |
84| bundleCodeDir       | string   | Yes  | No  | Path for storing the application's installation package, that is, installation directory of the application on the internal storage.                  |
85| cacheDir | string | Yes| No| Path for storing the cache files, that is, cache directory of the application on the internal storage.<br>It is the content of **Storage** of an application under **Settings > Apps & services > Apps**.|
86| filesDir            | string   | Yes  | No  | Path for storing the common files, that is, 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.|
87| preferencesDir      | string   | Yes  | Yes  | Path for storing the preference files, that is, preferences directory of the application.                |
88| tempDir             | string   | Yes  | No  | Path for storing the temporary files.<br>Files in this directory are deleted after the application is uninstalled.|
89| databaseDir         | string   | Yes  | No  | Path for storing the application's database, that is, storage directory of the local database.                        |
90| distributedFilesDir | string | Yes| No| Path for storing the distributed files.|
91
92The 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.
93
94**Figure 1** Application development paths obtained from context
95
96![context-dir](figures/context-dir.png)
97
98- 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.
99    | Name| Path|
100  | -------- | -------- |
101  | bundleCodeDir | {Path prefix}/el1/bundle/|
102  | cacheDir | {Path prefix}/{Encryption level}/base/cache/|
103  | filesDir | {Path prefix}/{Encryption level}/base/files/|
104  | preferencesDir | {Path prefix}/{Encryption level}/base/preferences/|
105  | tempDir | {Path prefix}/{Encryption level}/base/temp/|
106  | databaseDir | {Path prefix}/{Encryption level}/database/|
107  | distributedFilesDir | {Path prefix}/el2/distributedFiles/|
108
109- 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.
110    | Name| Path|
111  | -------- | -------- |
112  | bundleCodeDir | {Path prefix}/el1/bundle/|
113  | cacheDir | {Path prefix}/{Encryption level}/base/**haps/{moduleName}**/cache/|
114  | filesDir | {Path prefix}/{Encryption level}/base/**haps/{moduleName}**/files/|
115  | preferencesDir | {Path prefix}/{Encryption level}/base/**haps/{moduleName}**/preferences/|
116  | tempDir | {Path prefix}/{Encryption level}/base/**haps/{moduleName}**/temp/|
117  | databaseDir | {Path prefix}/{Encryption level}/database/**{moduleName}**/|
118  | distributedFilesDir | {Path prefix}/el2/distributedFiles/**{moduleName}**/|
119
120The sample code for obtaining the application development paths is as follows:
121
122
123```ts
124import UIAbility from '@ohos.app.ability.UIAbility';
125
126export default class EntryAbility extends UIAbility {
127  onCreate(want, launchParam) {
128    let cacheDir = this.context.cacheDir;
129    let tempDir = this.context.tempDir;
130    let filesDir = this.context.filesDir;
131    let databaseDir = this.context.databaseDir;
132    let bundleCodeDir = this.context.bundleCodeDir;
133    let distributedFilesDir = this.context.distributedFilesDir;
134    let preferencesDir = this.context.preferencesDir;
135    ...
136  }
137}
138```
139
140> **NOTE**
141>
142> The sample code obtains the sandbox path of the application development path. The absolute path can be obtained by running the **find / -name <fileName>** command in the hdc shell after file creation or modification.
143
144### Obtaining and Modifying Encryption Levels
145
146Encrypting application files enhances data security by preventing files from unauthorized access. Different application files require different levels of protection. For private files, such as alarms and wallpapers, the application must place them in a directory with the device-level encryption (EL1) to ensure that they can be accessed before the user enters the password. For sensitive files, such as personal privacy data, the application must place them in a directory with the user-level encryption (EL2).
147
148In 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.
149
150> **NOTE**
151>
152> - AreaMode.EL1: device-level encryption. Directories with this encryption level are accessible after the device is powered on.
153>
154> - AreaMode.EL2: user-level encryption. Directories with this encryption level are accessible only after the device is powered on and the password is entered (for the first time).
155
156You can obtain and set the encryption level by reading and writing the [area attribute in Context](../reference/apis/js-apis-inner-application-context.md).
157
158```ts
159import UIAbility from '@ohos.app.ability.UIAbility';
160
161export default class EntryAbility extends UIAbility {
162  onCreate(want, launchParam) {
163    // Before storing common information, switch the encryption level to EL1.
164    if (this.context.area === 1) {// Obtain the area.
165      this.context.area = 0; // Modify the area.
166    }
167    // Store common information.
168
169    // Before storing sensitive information, switch the encryption level to EL2.
170    if (this.context.area === 0) { // Obtain the area.
171      this.context.area = 1; // Modify the area.
172    }
173    // Store sensitive information.
174  }
175}
176```
177
178
179### Creating Context of Another Application or Module
180
181The base class **Context** provides [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) to create 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.
182
183- Call **createBundleContext(bundleName:string)** to create the context of another application.
184  > **NOTE**
185  >
186  > To obtain the context of another application:
187  >
188  > - Request the **ohos.permission.GET_BUNDLE_INFO_PRIVILEGED** permission. For details, see [Declaring Permissions in the Configuration File](../security/accesstoken-guidelines.md#declaring-permissions-in-the-configuration-file).
189  >
190  > - This is a system API and cannot be called by third-party applications.
191
192  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.
193
194  ```ts
195  import UIAbility from '@ohos.app.ability.UIAbility';
196
197  export default class EntryAbility extends UIAbility {
198    onCreate(want, launchParam) {
199      let bundleName2 = 'com.example.application';
200      let context2 = this.context.createBundleContext(bundleName2);
201      let label2 = context2.applicationInfo.label;
202      ...
203    }
204  }
205  ```
206
207- 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.
208  > **NOTE**
209  >
210  > To obtain the context of a specified module of another application:
211  >
212  > - Request the **ohos.permission.GET_BUNDLE_INFO_PRIVILEGED** permission. For details, see [Declaring Permissions in the Configuration File](../security/accesstoken-guidelines.md#declaring-permissions-in-the-configuration-file).
213  >
214  > - This is a system API and cannot be called by third-party applications.
215
216  ```ts
217  import UIAbility from '@ohos.app.ability.UIAbility';
218
219  export default class EntryAbility extends UIAbility {
220    onCreate(want, launchParam) {
221      let bundleName2 = 'com.example.application';
222      let moduleName2 = 'module1';
223      let context2 = this.context.createModuleContext(bundleName2, moduleName2);
224      ...
225    }
226  }
227  ```
228
229- 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.
230
231  ```ts
232  import UIAbility from '@ohos.app.ability.UIAbility';
233
234  export default class EntryAbility extends UIAbility {
235    onCreate(want, launchParam) {
236      let moduleName2 = 'module1';
237      let context2 = this.context.createModuleContext(moduleName2);
238      ...
239    }
240  }
241  ```
242
243
244### Subscribing to UIAbility Lifecycle Changes in a Process
245
246In 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 UIAbility lifecycle changes in a process.
247
248[ApplicationContext](../reference/apis/js-apis-inner-application-applicationContext.md) provides APIs for subscribing to UIAbility lifecycle changes in a process. When the UIAbility 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. Each 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/js-apis-inner-application-uiAbilityContext.md) as an example.
249
250
251```ts
252import UIAbility from '@ohos.app.ability.UIAbility';
253import window from '@ohos.window';
254
255const TAG: string = '[Example].[Entry].[EntryAbility]';
256
257export default class EntryAbility extends UIAbility {
258  // Define a lifecycle ID.
259  lifecycleId: number;
260
261  onCreate(want, launchParam) {
262    // Define a lifecycle callback object.
263    let abilityLifecycleCallback = {
264      // Called when a UIAbility is created.
265      onAbilityCreate(uiAbility) {
266        console.info(TAG, `onAbilityCreate uiAbility.launchWant: ${JSON.stringify(uiAbility.launchWant)}`);
267      },
268      // Called when a window is created.
269      onWindowStageCreate(uiAbility, windowStage: window.WindowStage) {
270        console.info(TAG, `onWindowStageCreate uiAbility.launchWant: ${JSON.stringify(uiAbility.launchWant)}`);
271        console.info(TAG, `onWindowStageCreate windowStage: ${JSON.stringify(windowStage)}`);
272      },
273      // Called when the window becomes active.
274      onWindowStageActive(uiAbility, windowStage: window.WindowStage) {
275        console.info(TAG, `onWindowStageActive uiAbility.launchWant: ${JSON.stringify(uiAbility.launchWant)}`);
276        console.info(TAG, `onWindowStageActive windowStage: ${JSON.stringify(windowStage)}`);
277      },
278      // Called when the window becomes inactive.
279      onWindowStageInactive(uiAbility, windowStage: window.WindowStage) {
280        console.info(TAG, `onWindowStageInactive uiAbility.launchWant: ${JSON.stringify(uiAbility.launchWant)}`);
281        console.info(TAG, `onWindowStageInactive windowStage: ${JSON.stringify(windowStage)}`);
282      },
283      // Called when the window is destroyed.
284      onWindowStageDestroy(uiAbility, windowStage: window.WindowStage) {
285        console.info(TAG, `onWindowStageDestroy uiAbility.launchWant: ${JSON.stringify(uiAbility.launchWant)}`);
286        console.info(TAG, `onWindowStageDestroy windowStage: ${JSON.stringify(windowStage)}`);
287      },
288      // Called when the UIAbility is destroyed.
289      onAbilityDestroy(uiAbility) {
290        console.info(TAG, `onAbilityDestroy uiAbility.launchWant: ${JSON.stringify(uiAbility.launchWant)}`);
291      },
292      // Called when the UIAbility is switched from the background to the foreground.
293      onAbilityForeground(uiAbility) {
294        console.info(TAG, `onAbilityForeground uiAbility.launchWant: ${JSON.stringify(uiAbility.launchWant)}`);
295      },
296      // Called when the UIAbility is switched from the foreground to the background.
297      onAbilityBackground(uiAbility) {
298        console.info(TAG, `onAbilityBackground uiAbility.launchWant: ${JSON.stringify(uiAbility.launchWant)}`);
299      },
300      // Called when UIAbility is continued on another device.
301      onAbilityContinue(uiAbility) {
302        console.info(TAG, `onAbilityContinue uiAbility.launchWant: ${JSON.stringify(uiAbility.launchWant)}`);
303      }
304    }
305    // Obtain the application context.
306    let applicationContext = this.context.getApplicationContext();
307    // Register the application lifecycle callback.
308    this.lifecycleId = applicationContext.on('abilityLifecycle', abilityLifecycleCallback);
309    console.info(TAG, `register callback number: ${this.lifecycleId}`);
310  }
311
312  ...
313
314  onDestroy() {
315    // Obtain the application context.
316    let applicationContext = this.context.getApplicationContext();
317    // Deregister the application lifecycle callback.
318    applicationContext.off('abilityLifecycle', this.lifecycleId);
319  }
320}
321```
322