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