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 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 Application File Paths](#obtaining-application-file-paths) 74- [Obtaining and Modifying Encryption Levels](#obtaining-and-modifying-encryption-levels) 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 Application File Paths 80 81The 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). 82 83The application file paths obtained by the preceding contexts are different. 84 85- 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. 86 87 | Name| Path| 88 | -------- | -------- | 89 | bundleCodeDir | \<Path prefix>/el1/bundle/ | 90 | cacheDir | \<Path prefix>/\<Encryption level>/base/cache/ | 91 | filesDir | \<Path prefix>/\<Encryption level>/base/files/ | 92 | preferencesDir | \<Path prefix>/\<Encryption level>/base/preferences/ | 93 | tempDir | \<Path prefix>/\<Encryption level>/base/temp/ | 94 | databaseDir | \<Path prefix>/\<Encryption level>/database/ | 95 | distributedFilesDir | \<Path prefix>/el2/distributedFiles/ | 96 97 The sample code is as follows: 98 99 ```ts 100 import UIAbility from '@ohos.app.ability.UIAbility'; 101 102 export default class EntryAbility extends UIAbility { 103 onCreate(want, launchParam) { 104 let applicationContext = this.context.getApplicationContext(); 105 let cacheDir = applicationContext.cacheDir; 106 let tempDir = applicationContext.tempDir; 107 let filesDir = applicationContext.filesDir; 108 let databaseDir = applicationContext.databaseDir; 109 let bundleCodeDir = applicationContext.bundleCodeDir; 110 let distributedFilesDir = applicationContext.distributedFilesDir; 111 let preferencesDir = applicationContext.preferencesDir; 112 ... 113 } 114 } 115 ``` 116 117- 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. 118 119 | Name| Path| 120 | -------- | -------- | 121 | bundleCodeDir | \<Path prefix>/el1/bundle/ | 122 | cacheDir | \<Path prefix>/\<Encryption level>/base/**haps/\<module-name>**/cache/ | 123 | filesDir | \<Path prefix>/\<Encryption level>/base/**haps/\<module-name>**/files/ | 124 | preferencesDir | \<Path prefix>/\<Encryption level>/base/**haps/\<module-name>**/preferences/ | 125 | tempDir | \<Path prefix>/\<Encryption level>/base/**haps/\<module-name>**/temp/ | 126 | databaseDir | \<Path prefix>/\<Encryption level>/database/**\<module-name>**/ | 127 | distributedFilesDir | \<Path prefix>/el2/distributedFiles/**\<module-name>**/ | 128 129 The sample code is as follows: 130 131 ```ts 132 import UIAbility from '@ohos.app.ability.UIAbility'; 133 134 export default class EntryAbility extends UIAbility { 135 onCreate(want, launchParam) { 136 let cacheDir = this.context.cacheDir; 137 let tempDir = this.context.tempDir; 138 let filesDir = this.context.filesDir; 139 let databaseDir = this.context.databaseDir; 140 let bundleCodeDir = this.context.bundleCodeDir; 141 let distributedFilesDir = this.context.distributedFilesDir; 142 let preferencesDir = this.context.preferencesDir; 143 ... 144 } 145 } 146 ``` 147 148 149### Obtaining and Modifying Encryption Levels 150 151Encrypting 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). 152 153In 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. 154 155> **NOTE** 156> 157> - AreaMode.EL1: device-level encryption. Directories with this encryption level are accessible after the device is powered on. 158> 159> - 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). 160 161You can obtain and set the encryption level by reading and writing the **area** attribute in [Context](../reference/apis/js-apis-inner-application-context.md). 162 163```ts 164import UIAbility from '@ohos.app.ability.UIAbility'; 165import contextConstant from '@ohos.app.ability.contextConstant'; 166 167export default class EntryAbility extends UIAbility { 168 onCreate(want, launchParam) { 169 // Before storing common information, switch the encryption level to EL1. 170 if (this.context.area === contextConstant.AreaMode.EL2) { // Obtain the area. 171 this.context.area = contextConstant.AreaMode.EL1; // Modify the area. 172 } 173 // Store common information. 174 175 // Before storing sensitive information, switch the encryption level to EL2. 176 if (this.context.area === contextConstant.AreaMode.EL1) { // Obtain the area. 177 this.context.area = contextConstant.AreaMode.EL2; // Modify the area. 178 } 179 // Store sensitive information. 180 } 181} 182``` 183 184 185### Creating Context of Another Application or Module 186 187The 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. 188 189- Call **createBundleContext(bundleName:string)** to create the context of another application. 190 > **NOTE** 191 > 192 > To obtain the context of another application: 193 > 194 > - 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). 195 > 196 > - This is a system API and cannot be called by third-party applications. 197 198 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. 199 200 ```ts 201 import UIAbility from '@ohos.app.ability.UIAbility'; 202 203 export default class EntryAbility extends UIAbility { 204 onCreate(want, launchParam) { 205 let bundleName2 = 'com.example.application'; 206 let context2 = this.context.createBundleContext(bundleName2); 207 let label2 = context2.applicationInfo.label; 208 ... 209 } 210 } 211 ``` 212 213- 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. 214 > **NOTE** 215 > 216 > To obtain the context of a specified module of another application: 217 > 218 > - 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). 219 > 220 > - This is a system API and cannot be called by third-party applications. 221 222 ```ts 223 import UIAbility from '@ohos.app.ability.UIAbility'; 224 225 export default class EntryAbility extends UIAbility { 226 onCreate(want, launchParam) { 227 let bundleName2 = 'com.example.application'; 228 let moduleName2 = 'module1'; 229 let context2 = this.context.createModuleContext(bundleName2, moduleName2); 230 ... 231 } 232 } 233 ``` 234 235- 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. 236 237 ```ts 238 import UIAbility from '@ohos.app.ability.UIAbility'; 239 240 export default class EntryAbility extends UIAbility { 241 onCreate(want, launchParam) { 242 let moduleName2 = 'module1'; 243 let context2 = this.context.createModuleContext(moduleName2); 244 ... 245 } 246 } 247 ``` 248 249 250### Subscribing to UIAbility Lifecycle Changes in a Process 251 252In 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. 253 254[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. 255 256 257```ts 258import UIAbility from '@ohos.app.ability.UIAbility'; 259import window from '@ohos.window'; 260 261const TAG: string = '[Example].[Entry].[EntryAbility]'; 262 263export default class EntryAbility extends UIAbility { 264 // Define a lifecycle ID. 265 lifecycleId: number; 266 267 onCreate(want, launchParam) { 268 // Define a lifecycle callback object. 269 let abilityLifecycleCallback = { 270 // Called when a UIAbility is created. 271 onAbilityCreate(uiAbility) { 272 console.info(TAG, `onAbilityCreate uiAbility.launchWant: ${JSON.stringify(uiAbility.launchWant)}`); 273 }, 274 // Called when a window is created. 275 onWindowStageCreate(uiAbility, windowStage: window.WindowStage) { 276 console.info(TAG, `onWindowStageCreate uiAbility.launchWant: ${JSON.stringify(uiAbility.launchWant)}`); 277 console.info(TAG, `onWindowStageCreate windowStage: ${JSON.stringify(windowStage)}`); 278 }, 279 // Called when the window becomes active. 280 onWindowStageActive(uiAbility, windowStage: window.WindowStage) { 281 console.info(TAG, `onWindowStageActive uiAbility.launchWant: ${JSON.stringify(uiAbility.launchWant)}`); 282 console.info(TAG, `onWindowStageActive windowStage: ${JSON.stringify(windowStage)}`); 283 }, 284 // Called when the window becomes inactive. 285 onWindowStageInactive(uiAbility, windowStage: window.WindowStage) { 286 console.info(TAG, `onWindowStageInactive uiAbility.launchWant: ${JSON.stringify(uiAbility.launchWant)}`); 287 console.info(TAG, `onWindowStageInactive windowStage: ${JSON.stringify(windowStage)}`); 288 }, 289 // Called when the window is destroyed. 290 onWindowStageDestroy(uiAbility, windowStage: window.WindowStage) { 291 console.info(TAG, `onWindowStageDestroy uiAbility.launchWant: ${JSON.stringify(uiAbility.launchWant)}`); 292 console.info(TAG, `onWindowStageDestroy windowStage: ${JSON.stringify(windowStage)}`); 293 }, 294 // Called when the UIAbility is destroyed. 295 onAbilityDestroy(uiAbility) { 296 console.info(TAG, `onAbilityDestroy uiAbility.launchWant: ${JSON.stringify(uiAbility.launchWant)}`); 297 }, 298 // Called when the UIAbility is switched from the background to the foreground. 299 onAbilityForeground(uiAbility) { 300 console.info(TAG, `onAbilityForeground uiAbility.launchWant: ${JSON.stringify(uiAbility.launchWant)}`); 301 }, 302 // Called when the UIAbility is switched from the foreground to the background. 303 onAbilityBackground(uiAbility) { 304 console.info(TAG, `onAbilityBackground uiAbility.launchWant: ${JSON.stringify(uiAbility.launchWant)}`); 305 }, 306 // Called when UIAbility is continued on another device. 307 onAbilityContinue(uiAbility) { 308 console.info(TAG, `onAbilityContinue uiAbility.launchWant: ${JSON.stringify(uiAbility.launchWant)}`); 309 } 310 } 311 // Obtain the application context. 312 let applicationContext = this.context.getApplicationContext(); 313 // Register the application lifecycle callback. 314 this.lifecycleId = applicationContext.on('abilityLifecycle', abilityLifecycleCallback); 315 console.info(TAG, `register callback number: ${this.lifecycleId}`); 316 } 317 318 ... 319 320 onDestroy() { 321 // Obtain the application context. 322 let applicationContext = this.context.getApplicationContext(); 323 // Deregister the application lifecycle callback. 324 applicationContext.off('abilityLifecycle', this.lifecycleId); 325 } 326} 327``` 328