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 file path), and **area** (encryption 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**. 7 8- The figure below illustrates the inheritance relationship of contexts. 9 10  11 12- The figure below illustrates the holding relationship of contexts. 13 14  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 import AbilityConstant from '@ohos.app.ability.AbilityConstant'; 22 import Want from '@ohos.app.ability.Want'; 23 export default class EntryAbility extends UIAbility { 24 onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) { 25 let uiAbilityContext = this.context; 26 ... 27 } 28 } 29 ``` 30 31 > **NOTE** 32 > 33 > 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). 34 - Scenario-specific [ExtensionContext](../reference/apis/js-apis-inner-application-extensionContext.md): For example, ServiceExtensionContext, inherited from ExtensionContext, provides APIs related to background services. 35 36 ```ts 37 import ServiceExtensionAbility from '@ohos.app.ability.ServiceExtensionAbility'; 38 import Want from '@ohos.app.ability.Want'; 39 export default class MyService extends ServiceExtensionAbility { 40 onCreate(want: Want) { 41 let serviceExtensionContext = this.context; 42 ... 43 } 44 } 45 ``` 46 - [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**. 47 48 ```ts 49 import AbilityStage from '@ohos.app.ability.AbilityStage'; 50 export default class MyAbilityStage extends AbilityStage { 51 onCreate() { 52 let abilityStageContext = this.context; 53 ... 54 } 55 } 56 ``` 57 - [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. 58 59 ```ts 60 import UIAbility from '@ohos.app.ability.UIAbility'; 61 import AbilityConstant from '@ohos.app.ability.AbilityConstant'; 62 import Want from '@ohos.app.ability.Want'; 63 export default class EntryAbility extends UIAbility { 64 onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) { 65 let applicationContext = this.context.getApplicationContext(); 66 ... 67 } 68 } 69 ``` 70 71 72## Typical Usage Scenarios of Context 73 74 75This topic describes how to use the context in the following scenarios: 76 77 78- [Obtaining Application File Paths](#obtaining-application-file-paths) 79- [Obtaining and Modifying Encryption Levels](#obtaining-and-modifying-encryption-levels) 80- [Creating Context of Another Application or Module](#creating-context-of-another-application-or-module) 81- [Subscribing to UIAbility Lifecycle Changes in a Process](#subscribing-to-uiability-lifecycle-changes-in-a-process) 82 83 84### Obtaining Application File Paths 85 86The base class [Context](../reference/apis/js-apis-inner-application-context.md) provides the capability of obtaining application file paths. **ApplicationContext**, **AbilityStageContext**, **UIAbilityContext**, and **ExtensionContext** inherit this capability. The application file paths are a type of application sandbox paths. For details, see [Application Sandbox Directory](../file-management/app-sandbox-directory.md). 87 88The application file paths obtained by the preceding contexts are different. 89 90- The application file path obtained through **ApplicationContext** is at the application level. This path is recommended for storing global application information, and the files in the path will be deleted when the application is uninstalled. 91 92 | Name| Path| 93 | -------- | -------- | 94 | bundleCodeDir | \<Path prefix>/el1/bundle| 95 | cacheDir | \<Path prefix>/\<Encryption level>/base/cache| 96 | filesDir | \<Path prefix>/\<Encryption level>/base/files| 97 | preferencesDir | \<Path prefix>/\<Encryption level>/base/preferences| 98 | tempDir | \<Path prefix>/\<Encryption level>/base/temp| 99 | databaseDir | \<Path prefix>/\<Encryption level>/database| 100 | distributedFilesDir | \<Path prefix>/el2/distributedFiles| 101 102 The sample code is as follows: 103 104 ```ts 105 import UIAbility from '@ohos.app.ability.UIAbility'; 106 import AbilityConstant from '@ohos.app.ability.AbilityConstant'; 107 import Want from '@ohos.app.ability.Want'; 108 109 export default class EntryAbility extends UIAbility { 110 onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) { 111 let applicationContext = this.context.getApplicationContext(); 112 let cacheDir = applicationContext.cacheDir; 113 let tempDir = applicationContext.tempDir; 114 let filesDir = applicationContext.filesDir; 115 let databaseDir = applicationContext.databaseDir; 116 let bundleCodeDir = applicationContext.bundleCodeDir; 117 let distributedFilesDir = applicationContext.distributedFilesDir; 118 let preferencesDir = applicationContext.preferencesDir; 119 ... 120 // Obtain the application file path. 121 let filePath = tempDir + 'test.txt'; 122 console.info(`filePath: ${filePath}`); 123 } 124 } 125 ``` 126 127- The application file path obtained through **AbilityStageContext**, **UIAbilityContext**, or **ExtensionContext** is at the HAP level. This path is recommended for storing HAP-related information, and the files in this path are deleted when the HAP is uninstalled. However, the deletion does not affect the files in the application-level path unless all HAPs of the application are uninstalled. 128 129 | Name| Path| 130 | -------- | -------- | 131 | bundleCodeDir | \<Path prefix>/el1/bundle| 132 | cacheDir | \<Path prefix>/\<Encryption level>/base/**haps/\<module-name>**/cache| 133 | filesDir | \<Path prefix>/\<Encryption level>/base/**haps/\<module-name>**/files| 134 | preferencesDir | \<Path prefix>/\<Encryption level>/base/**haps/\<module-name>**/preferences| 135 | tempDir | \<Path prefix>/\<Encryption level>/base/**haps/\<module-name>**/temp| 136 | databaseDir | \<Path prefix>/\<Encryption level>/database/**\<module-name>**| 137 | distributedFilesDir | \<Path prefix>/el2/distributedFiles/**\<module-name>**| 138 139 The sample code is as follows: 140 141 ```ts 142 import UIAbility from '@ohos.app.ability.UIAbility'; 143 import AbilityConstant from '@ohos.app.ability.AbilityConstant'; 144 import Want from '@ohos.app.ability.Want'; 145 146 export default class EntryAbility extends UIAbility { 147 onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) { 148 let cacheDir = this.context.cacheDir; 149 let tempDir = this.context.tempDir; 150 let filesDir = this.context.filesDir; 151 let databaseDir = this.context.databaseDir; 152 let bundleCodeDir = this.context.bundleCodeDir; 153 let distributedFilesDir = this.context.distributedFilesDir; 154 let preferencesDir = this.context.preferencesDir; 155 ... 156 // Obtain the application file path. 157 let filePath = tempDir + 'test.txt'; 158 console.info(`filePath: ${filePath}`); 159 } 160 } 161 ``` 162 163 164### Obtaining and Modifying Encryption Levels 165 166Encrypting 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). 167 168In 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. 169 170> **NOTE** 171> 172> - AreaMode.EL1: device-level encryption. Directories with this encryption level are accessible after the device is powered on. 173> 174> - 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). 175 176You can obtain and set the encryption level by reading and writing the **area** attribute in [Context](../reference/apis/js-apis-inner-application-context.md). 177 178```ts 179import UIAbility from '@ohos.app.ability.UIAbility'; 180import contextConstant from '@ohos.app.ability.contextConstant'; 181import AbilityConstant from '@ohos.app.ability.AbilityConstant'; 182import Want from '@ohos.app.ability.Want'; 183 184export default class EntryAbility extends UIAbility { 185 onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) { 186 // Before storing common information, switch the encryption level to EL1. 187 if (this.context.area === contextConstant.AreaMode.EL2) { // Obtain the area. 188 this.context.area = contextConstant.AreaMode.EL1; // Modify the area. 189 } 190 // Store common information. 191 192 // Before storing sensitive information, switch the encryption level to EL2. 193 if (this.context.area === contextConstant.AreaMode.EL1) { // Obtain the area. 194 this.context.area = contextConstant.AreaMode.EL2; // Modify the area. 195 } 196 // Store sensitive information. 197 } 198} 199``` 200 201 202### Creating Context of Another Application or Module 203 204The 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 application file paths](#obtaining-application-development-paths) of other modules. 205 206- Call **createBundleContext(bundleName:string)** to create the context of another application. 207 > **NOTE** 208 > 209 > To obtain the context of another application: 210 > 211 > - 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). 212 > 213 > - This is a system API and cannot be called by third-party applications. 214 215 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. 216 217 ```ts 218 import UIAbility from '@ohos.app.ability.UIAbility'; 219 import AbilityConstant from '@ohos.app.ability.AbilityConstant'; 220 import Want from '@ohos.app.ability.Want'; 221 222 export default class EntryAbility extends UIAbility { 223 onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) { 224 let bundleName2 = 'com.example.application'; 225 let context2 = this.context.createBundleContext(bundleName2); 226 let label2 = context2.applicationInfo.label; 227 ... 228 } 229 } 230 ``` 231 232- 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. 233 > **NOTE** 234 > 235 > To obtain the context of a specified module of another application: 236 > 237 > - 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). 238 > 239 > - This is a system API and cannot be called by third-party applications. 240 241 ```ts 242 import UIAbility from '@ohos.app.ability.UIAbility'; 243 import AbilityConstant from '@ohos.app.ability.AbilityConstant'; 244 import Want from '@ohos.app.ability.Want'; 245 246 export default class EntryAbility extends UIAbility { 247 onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) { 248 let bundleName2 = 'com.example.application'; 249 let moduleName2 = 'module1'; 250 let context2 = this.context.createModuleContext(bundleName2, moduleName2); 251 ... 252 } 253 } 254 ``` 255 256- 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. 257 258 ```ts 259 import UIAbility from '@ohos.app.ability.UIAbility'; 260 import AbilityConstant from '@ohos.app.ability.AbilityConstant'; 261 import Want from '@ohos.app.ability.Want'; 262 263 export default class EntryAbility extends UIAbility { 264 onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) { 265 let moduleName2 = 'module1'; 266 let context2 = this.context.createModuleContext(moduleName2); 267 ... 268 } 269 } 270 ``` 271 272 273### Subscribing to UIAbility Lifecycle Changes in a Process 274 275In 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. 276 277[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. 278 279 280```ts 281import UIAbility from '@ohos.app.ability.UIAbility'; 282import AbilityConstant from '@ohos.app.ability.AbilityConstant'; 283import AbilityLifecycleCallback from '@ohos.app.ability.AbilityLifecycleCallback'; 284import Want from '@ohos.app.ability.Want'; 285import window from '@ohos.window'; 286 287const TAG: string = '[Example].[Entry].[EntryAbility]'; 288 289export default class EntryAbility extends UIAbility { 290 // Define a lifecycle ID. 291 lifecycleId: number = -1; 292 293 onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) { 294 // Define a lifecycle callback object. 295 let abilityLifecycleCallback: AbilityLifecycleCallback = { 296 // Called when a UIAbility is created. 297 onAbilityCreate(uiAbility) { 298 console.info(TAG, `onAbilityCreate uiAbility.launchWant: ${JSON.stringify(uiAbility.launchWant)}`); 299 }, 300 // Called when a window is created. 301 onWindowStageCreate(uiAbility, windowStage: window.WindowStage) { 302 console.info(TAG, `onWindowStageCreate uiAbility.launchWant: ${JSON.stringify(uiAbility.launchWant)}`); 303 console.info(TAG, `onWindowStageCreate windowStage: ${JSON.stringify(windowStage)}`); 304 }, 305 // Called when the window becomes active. 306 onWindowStageActive(uiAbility, windowStage: window.WindowStage) { 307 console.info(TAG, `onWindowStageActive uiAbility.launchWant: ${JSON.stringify(uiAbility.launchWant)}`); 308 console.info(TAG, `onWindowStageActive windowStage: ${JSON.stringify(windowStage)}`); 309 }, 310 // Called when the window becomes inactive. 311 onWindowStageInactive(uiAbility, windowStage: window.WindowStage) { 312 console.info(TAG, `onWindowStageInactive uiAbility.launchWant: ${JSON.stringify(uiAbility.launchWant)}`); 313 console.info(TAG, `onWindowStageInactive windowStage: ${JSON.stringify(windowStage)}`); 314 }, 315 // Called when the window is destroyed. 316 onWindowStageDestroy(uiAbility, windowStage: window.WindowStage) { 317 console.info(TAG, `onWindowStageDestroy uiAbility.launchWant: ${JSON.stringify(uiAbility.launchWant)}`); 318 console.info(TAG, `onWindowStageDestroy windowStage: ${JSON.stringify(windowStage)}`); 319 }, 320 // Called when the UIAbility is destroyed. 321 onAbilityDestroy(uiAbility) { 322 console.info(TAG, `onAbilityDestroy uiAbility.launchWant: ${JSON.stringify(uiAbility.launchWant)}`); 323 }, 324 // Called when the UIAbility is switched from the background to the foreground. 325 onAbilityForeground(uiAbility) { 326 console.info(TAG, `onAbilityForeground uiAbility.launchWant: ${JSON.stringify(uiAbility.launchWant)}`); 327 }, 328 // Called when the UIAbility is switched from the foreground to the background. 329 onAbilityBackground(uiAbility) { 330 console.info(TAG, `onAbilityBackground uiAbility.launchWant: ${JSON.stringify(uiAbility.launchWant)}`); 331 }, 332 // Called when UIAbility is continued on another device. 333 onAbilityContinue(uiAbility) { 334 console.info(TAG, `onAbilityContinue uiAbility.launchWant: ${JSON.stringify(uiAbility.launchWant)}`); 335 } 336 } 337 // Obtain the application context. 338 let applicationContext = this.context.getApplicationContext(); 339 // Register the application lifecycle callback. 340 this.lifecycleId = applicationContext.on('abilityLifecycle', abilityLifecycleCallback); 341 console.info(TAG, `register callback number: ${this.lifecycleId}`); 342 } 343 344 ... 345 346 onDestroy() { 347 // Obtain the application context. 348 let applicationContext = this.context.getApplicationContext(); 349 // Deregister the application lifecycle callback. 350 applicationContext.off('abilityLifecycle', this.lifecycleId); 351 } 352} 353``` 354