• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Context Usage
2
3## Context Overview
4
5**Context** provides the capability of obtaining contextual information of an application.
6
7The OpenHarmony application framework has two models: Feature Ability (FA) model and stage model. Correspondingly, there are two sets of context mechanisms. **application/BaseContext** is a common context base class. It uses the **stageMode** attribute to specify whether the context is used for the stage model.
8
9- FA model
10
11  Only the methods in **app/Context** can be used for the context in the FA model. Both the application-level context and ability-level context are instances of this type. If an ability-level method is invoked in the application-level context, an error occurs. Therefore, you must pay attention to the actual meaning of the **Context** instance.
12
13- Stage model
14
15  The stage model has the following types of contexts: **application/Context**, **application/ApplicationContext**, **application/AbilityStageContext**, **application/ExtensionContext**, **application/AbilityContext**, and **application/FormExtensionContext**. For details about these contexts and how to use them, see [Context in the Stage Model](#context-in-the-stage-model).
16
17![contextIntroduction](figures/contextIntroduction.png)
18
19## Context in the FA Model
20
21Only the methods in **app/Context** can be used for the context in the FA model.
22
23The FA model has only one context definition. All capabilities in the context are provided through methods. The context uses these methods to extend the capabilities of the FA.
24
25**d.ts statement**
26
27https://gitee.com/openharmony/interface_sdk-js/blob/master/api/app/context.d.ts
28
29**Example**
30
31```javascript
32import featureAbility from '@ohos.ability.featureAbility'
33export default {
34  onCreate() {
35    // Obtain the context and call related APIs.
36    let context = featureAbility.getContext();
37    context.getBundleName((data, bundleName)=>{
38      console.info("ability bundleName:" + bundleName)
39    });
40    console.info('Application onCreate')
41  },
42  onDestroy() {
43    console.info('Application onDestroy')
44  },
45}
46```
47
48### Common Context-related Methods in the FA Model
49The following context-related methods are available in the FA model:
50```javascript
51setDisplayOrientation(orientation: bundle.DisplayOrientation, callback: AsyncCallback<void>): void
52setDisplayOrientation(orientation: bundle.DisplayOrientation): Promise<void>;
53```
54The methods are used to set the display orientation of the current ability.
55
56**Example**
57
58```javascript
59import featureAbility from '@ohos.ability.featureAbility'
60import bundle from '@ohos.bundle';
61
62export default {
63  onCreate() {
64    // Obtain the context and call related APIs.
65    let context = featureAbility.getContext();
66    context.setDisplayOrientation(bundle.DisplayOrientation.LANDSCAPE).then(() => {
67        console.log("Set display orientation.")
68    })
69    console.info('Application onCreate')
70  },
71  onDestroy() {
72    console.info('Application onDestroy')
73  },
74}
75```
76
77## Context in the Stage Model
78
79The following describes the contexts provided by the stage model in detail.
80
81### application/Context
82
83**application/Context** is the base class context. It provides basic application information, such as **resourceManager**, **applicationInfo**, **cacheDir**, and **area**. It also provides basic application methods such as **createModuleContext**.
84
85**d.ts statement**
86
87https://gitee.com/openharmony/interface_sdk-js/blob/master/api/application/Context.d.ts
88
89### application/ApplicationContext
90
91**application/ApplicationContext** is an application-level context. In addition to the capabilities provided by the base class context, the application-level context provides **registerAbilityLifecycleCallback** and **unregisterAbilityLifecycleCallback** to monitor the ability lifecycle in a process.
92
93**How to Obtain**
94
95Obtain the context by calling **context.getApplicationContext()** in **Ability**.
96
97**Example**
98
99```javascript
100import Ability from "@ohos.application.Ability";
101
102var lifecycleid;
103
104export default class MainAbility extends Ability {
105    onCreate() {
106        console.log("MainAbility onCreate")
107        let AbilityLifecycleCallback  =  {
108            onAbilityCreate(ability){
109                console.log("AbilityLifecycleCallback onAbilityCreate ability:" + JSON.stringify(ability));
110            },
111            onWindowStageCreate(ability, windowStage){
112                console.log("AbilityLifecycleCallback onWindowStageCreate ability:" + JSON.stringify(ability));
113                console.log("AbilityLifecycleCallback onWindowStageCreate windowStage:" + JSON.stringify(windowStage));
114            },
115            onWindowStageActive(ability, windowStage){
116                console.log("AbilityLifecycleCallback onWindowStageActive ability:" + JSON.stringify(ability));
117                console.log("AbilityLifecycleCallback onWindowStageActive windowStage:" + JSON.stringify(windowStage));
118            },
119            onWindowStageInactive(ability, windowStage){
120                console.log("AbilityLifecycleCallback onWindowStageInactive ability:" + JSON.stringify(ability));
121                console.log("AbilityLifecycleCallback onWindowStageInactive windowStage:" + JSON.stringify(windowStage));
122            },
123            onWindowStageDestroy(ability, windowStage){
124                console.log("AbilityLifecycleCallback onWindowStageDestroy ability:" + JSON.stringify(ability));
125                console.log("AbilityLifecycleCallback onWindowStageDestroy windowStage:" + JSON.stringify(windowStage));
126            },
127            onAbilityDestroy(ability){
128                console.log("AbilityLifecycleCallback onAbilityDestroy ability:" + JSON.stringify(ability));
129            },
130            onAbilityForeground(ability){
131                console.log("AbilityLifecycleCallback onAbilityForeground ability:" + JSON.stringify(ability));
132            },
133            onAbilityBackground(ability){
134                console.log("AbilityLifecycleCallback onAbilityBackground ability:" + JSON.stringify(ability));
135            },
136            onAbilityContinue(ability){
137                console.log("AbilityLifecycleCallback onAbilityContinue ability:" + JSON.stringify(ability));
138            }
139        }
140        // 1. Obtain applicationContext through the context attribute.
141        let applicationContext = this.context.getApplicationContext();
142        // 2. Use applicationContext to register and listen for the ability lifecycle in the application.
143        lifecycleid = applicationContext.registerAbilityLifecycleCallback(AbilityLifecycleCallback);
144        console.log("registerAbilityLifecycleCallback number: " + JSON.stringify(lifecycleid));
145    },
146    onDestroy() {
147        let applicationContext = this.context.getApplicationContext();
148        applicationContext.unregisterAbilityLifecycleCallback(lifecycleid, (error, data) => {
149            console.log("unregisterAbilityLifecycleCallback success, err: " + JSON.stringify(error));
150        });
151    }
152}
153```
154
155**d.ts statement**
156
157https://gitee.com/openharmony/interface_sdk-js/blob/master/api/application/ApplicationContext.d.ts
158
159### application/AbilityStageContext
160
161**application/AbilityStageContext** is the context for the HAP file. In addition to those provided by the base class **application/Context**, this context contains **HapModuleInfo** and **Configuration**.
162
163**How to Obtain**
164
165Obtain the context from the **context** attribute in **AbilityStage**.
166
167**Example**
168
169```javascript
170export default class MyAbilityStage extends AbilityStage {
171  onCreate() {
172    // The context attribute is of the AbilityStageContext type.
173    console.log('HapModuleInfo is ' + this.context.currentHapModuleInfo);
174  }
175}
176```
177
178**d.ts statement**
179
180https://gitee.com/openharmony/interface_sdk-js/blob/master/api/application/AbilityStageContext.d.ts
181
182### application/AbilityContext
183
184In the stage model, each ability has a context attribute.
185
186**Ability** provides methods to manage the ability lifecycle, and **AbilityContext** provides methods to operate abilities (such as **startAbility** and **connectAbility**).
187
188**How to Obtain**
189
190Obtain the context from the **context** attribute in **Ability**.
191
192**Example**
193
194```javascript
195import Ability from '@ohos.application.Ability'
196
197export default class MainAbility extends Ability {
198    onCreate(want, launchParam) {
199        console.log("[Demo] MainAbility onCreate")
200        globalThis.abilityWant = want;
201    }
202
203    onDestroy() {
204        console.log("[Demo] MainAbility onDestroy")
205    }
206
207    onWindowStageCreate(windowStage) {
208        // Set the main page for this ability when the main window is created.
209        console.log("[Demo] MainAbility onWindowStageCreate")
210
211        // Obtain AbilityContext and print the ability information.
212        let context = this.context;
213        console.log("[Demo] MainAbility bundleName " + context.abilityInfo.bundleName)
214
215        windowStage.loadContent("pages/index", (err, data) => {
216            if (err.code) {
217                console.error('Failed to load the content. Cause:' + JSON.stringify(err));
218                return;
219            }
220            console.info('Succeeded in loading the content. Data: ' + JSON.stringify(data))
221        });
222    }
223
224    onWindowStageDestroy() {
225        // Release the UI related resources when the main window is destroyed.
226        console.log("[Demo] MainAbility onWindowStageDestroy")
227    }
228
229    onForeground() {
230        // The ability is switched to run in the foreground.
231        console.log("[Demo] MainAbility onForeground")
232    }
233
234    onBackground() {
235        // The ability is switched to run in the background.
236        console.log("[Demo] MainAbility onBackground")
237    }
238};
239```
240
241### application/FormExtensionContext
242
243For details, see [FormExtensionContext](../reference/apis/js-apis-inner-application-formExtensionContext.md).
244
245### Obtaining the Context on an ArkTS Page
246
247In the stage model, in the onWindowStageCreate lifecycle of an ability, you can call **SetUIContent** of **WindowStage** to load an ArkTS page. In some scenarios, you need to obtain the context on the page to call related APIs.
248
249**How to Obtain**
250
251Use the API described in the table below to obtain the context associated with an ArkTS page.
252
253| API                               | Description                                                        |
254| :------------------------------------ | :----------------------------------------------------------- |
255| getContext(component: Object): Object | Obtains the **Context** object associated with a component on the page.<br>Since API version 9, this API is supported in ArkTS widgets.|
256
257**Example**
258
259```ts
260// MainAbility.ts
261import Ability from '@ohos.application.Ability'
262
263export default class MainAbility extends Ability {
264    onCreate(want, launchParam) {
265        console.log("[Demo] MainAbility onCreate")
266    }
267
268    onDestroy() {
269        console.log("[Demo] MainAbility onDestroy")
270    }
271
272    onWindowStageCreate(windowStage) {
273        // Load the index page and pass the current Context object.
274        windowStage.setUIContent(this.context, "pages/index", null)
275    }
276
277    onWindowStageDestroy() {}
278
279    onForeground() {}
280
281    onBackground() {}
282};
283```
284
285```ts
286// pages/index.ets
287import context from '@ohos.application.context'
288
289type Context = context.Context
290
291@Entry
292@Component
293struct Index {
294    build() {
295        Row() {
296            Column() {
297                Text('GetContext')
298                    .fontSize(50)
299                    .fontWeight(FontWeight.Bold)
300                    .onClick(() => {
301                        // Obtain the Context object associated with the current component.
302                        var context : Context = getContext(this) as Context
303                        console.info("CacheDir:" + context.cacheDir)
304                    })
305            }
306            .width('100%')
307        }
308        .height('100%')
309    }
310}
311```
312
313## Common Incorrect Usage
314
315**Error 1: Use globalThis to obtain the context in the stage model.**
316
317**Reason**
318
319In the FA model, each ability instance has a JS VM instance. Therefore, a global ability instance can be obtained from the **global** object of the JS engine. In the stage model, where all the processes of an application share a JS VM instance, there is no global ability instance, and using **globalThis** may cause an error or crash.
320