context-userguide.md 12.0 KB
Newer Older
W
wusongqing 已提交
1 2 3 4
# Context Usage

## Context Overview

W
wusongqing 已提交
5
**Context** provides the capability of obtaining contextual information of an application.
W
wusongqing 已提交
6

7
The 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.
W
wusongqing 已提交
8

9
- FA model 
G
Gloria 已提交
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.
G
Gloria 已提交
12
  
W
wusongqing 已提交
13
- Stage model 
G
Gloria 已提交
14
  
W
wusongqing 已提交
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).
W
wusongqing 已提交
16 17 18 19 20 21 22 23 24

![contextIntroduction](figures/contextIntroduction.png)

## Context in the FA Model

Only the methods in **app/Context** can be used for the context in the FA model.

The 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.

W
wusongqing 已提交
25
**d.ts statement**
W
wusongqing 已提交
26 27 28

https://gitee.com/openharmony/interface_sdk-js/blob/master/api/app/context.d.ts

W
wusongqing 已提交
29
**Example**
W
wusongqing 已提交
30 31 32 33 34

```javascript
import featureAbility from '@ohos.ability.featureAbility'
export default {
  onCreate() {
W
wusongqing 已提交
35
    // Obtain the context and call related APIs.
W
wusongqing 已提交
36
    let context = featureAbility.getContext();
W
wusongqing 已提交
37 38
    context.getBundleName((data, bundleName)=>{
      console.info("ability bundleName:" + bundleName)
W
wusongqing 已提交
39
    });
W
wusongqing 已提交
40
    console.info('Application onCreate')
W
wusongqing 已提交
41 42
  },
  onDestroy() {
W
wusongqing 已提交
43
    console.info('Application onDestroy')
W
wusongqing 已提交
44 45 46 47
  },
}
```

W
wusongqing 已提交
48 49 50 51 52 53 54 55 56
### Common Context-related Methods in the FA Model
The following context-related methods are available in the FA model:
```javascript
setDisplayOrientation(orientation: bundle.DisplayOrientation, callback: AsyncCallback<void>): void
setDisplayOrientation(orientation: bundle.DisplayOrientation): Promise<void>;
```
The methods are used to set the display orientation of the current ability.

**Example**
57

W
wusongqing 已提交
58 59
```javascript
import featureAbility from '@ohos.ability.featureAbility'
G
Gloria 已提交
60
import bundle from '@ohos.bundle';
W
wusongqing 已提交
61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76

export default {
  onCreate() {
    // Obtain the context and call related APIs.
    let context = featureAbility.getContext();
    context.setDisplayOrientation(bundle.DisplayOrientation.LANDSCAPE).then(() => {
        console.log("Set display orientation.")
    })
    console.info('Application onCreate')
  },
  onDestroy() {
    console.info('Application onDestroy')
  },
}
```

W
wusongqing 已提交
77 78
## Context in the Stage Model

W
wusongqing 已提交
79
The following describes the contexts provided by the stage model in detail.
W
wusongqing 已提交
80 81 82

### application/Context

G
Gloria 已提交
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**.
W
wusongqing 已提交
84 85 86 87 88 89

**d.ts statement**

https://gitee.com/openharmony/interface_sdk-js/blob/master/api/application/Context.d.ts

### application/ApplicationContext
W
wusongqing 已提交
90

W
wusongqing 已提交
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.
W
wusongqing 已提交
92 93 94

**How to Obtain**

W
wusongqing 已提交
95
Obtain the context by calling **context.getApplicationContext()** in **Ability**.
W
wusongqing 已提交
96 97 98 99

**Example**

```javascript
100
import UIAbility from '@ohos.app.ability.UIAbility';
W
wusongqing 已提交
101

W
wusongqing 已提交
102 103
var lifecycleid;

104
export default class EntryAbility extends UIAbility {
W
wusongqing 已提交
105
    onCreate() {
106
        console.log("EntryAbility onCreate")
W
wusongqing 已提交
107 108 109 110
        let AbilityLifecycleCallback  =  {
            onAbilityCreate(ability){
                console.log("AbilityLifecycleCallback onAbilityCreate ability:" + JSON.stringify(ability));        
            },
W
wusongqing 已提交
111 112 113
            onWindowStageCreate(ability, windowStage){
                console.log("AbilityLifecycleCallback onWindowStageCreate ability:" + JSON.stringify(ability)); 
                console.log("AbilityLifecycleCallback onWindowStageCreate windowStage:" + JSON.stringify(windowStage));           
W
wusongqing 已提交
114
            },
W
wusongqing 已提交
115 116 117 118 119 120 121 122 123 124 125
            onWindowStageActive(ability, windowStage){
                console.log("AbilityLifecycleCallback onWindowStageActive ability:" + JSON.stringify(ability)); 
                console.log("AbilityLifecycleCallback onWindowStageActive windowStage:" + JSON.stringify(windowStage));           
            },
            onWindowStageInactive(ability, windowStage){
                console.log("AbilityLifecycleCallback onWindowStageInactive ability:" + JSON.stringify(ability));
                console.log("AbilityLifecycleCallback onWindowStageInactive windowStage:" + JSON.stringify(windowStage));  
            },
            onWindowStageDestroy(ability, windowStage){
                console.log("AbilityLifecycleCallback onWindowStageDestroy ability:" + JSON.stringify(ability));
                console.log("AbilityLifecycleCallback onWindowStageDestroy windowStage:" + JSON.stringify(windowStage));  
W
wusongqing 已提交
126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144
            },
            onAbilityDestroy(ability){
                console.log("AbilityLifecycleCallback onAbilityDestroy ability:" + JSON.stringify(ability));             
            },
            onAbilityForeground(ability){
                console.log("AbilityLifecycleCallback onAbilityForeground ability:" + JSON.stringify(ability));             
            },
            onAbilityBackground(ability){
                console.log("AbilityLifecycleCallback onAbilityBackground ability:" + JSON.stringify(ability));              
            },
            onAbilityContinue(ability){
                console.log("AbilityLifecycleCallback onAbilityContinue ability:" + JSON.stringify(ability));
            }
        }
        // 1. Obtain applicationContext through the context attribute.
        let applicationContext = this.context.getApplicationContext();
        // 2. Use applicationContext to register and listen for the ability lifecycle in the application.
        lifecycleid = applicationContext.registerAbilityLifecycleCallback(AbilityLifecycleCallback);
        console.log("registerAbilityLifecycleCallback number: " + JSON.stringify(lifecycleid));       
145
    },
W
wusongqing 已提交
146 147 148
    onDestroy() {
        let applicationContext = this.context.getApplicationContext();
        applicationContext.unregisterAbilityLifecycleCallback(lifecycleid, (error, data) => {
149
            console.log("unregisterAbilityLifecycleCallback success, err: " + JSON.stringify(error));
W
wusongqing 已提交
150 151
        });
    }
W
wusongqing 已提交
152 153 154 155 156
}
```

**d.ts statement**

W
wusongqing 已提交
157
https://gitee.com/openharmony/interface_sdk-js/blob/master/api/application/ApplicationContext.d.ts
W
wusongqing 已提交
158 159 160 161 162 163 164 165 166 167 168 169 170 171 172

### application/AbilityStageContext

**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**.

**How to Obtain**

Obtain the context from the **context** attribute in **AbilityStage**.

**Example**

```javascript
export default class MyAbilityStage extends AbilityStage {
  onCreate() {
    // The context attribute is of the AbilityStageContext type.
W
wusongqing 已提交
173
    console.log('HapModuleInfo is ' + this.context.currentHapModuleInfo);
W
wusongqing 已提交
174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194
  }
}
```

**d.ts statement**

https://gitee.com/openharmony/interface_sdk-js/blob/master/api/application/AbilityStageContext.d.ts

### application/AbilityContext

In the stage model, each ability has a context attribute.

**Ability** provides methods to manage the ability lifecycle, and **AbilityContext** provides methods to operate abilities (such as **startAbility** and **connectAbility**).

**How to Obtain**

Obtain the context from the **context** attribute in **Ability**.

**Example**

```javascript
195
import UIAbility from '@ohos.app.ability.UIAbility';
W
wusongqing 已提交
196

197
export default class EntryAbility extends UIAbility {
W
wusongqing 已提交
198
    onCreate(want, launchParam) {
199
        console.log("[Demo] EntryAbility onCreate")
W
wusongqing 已提交
200
        globalThis.abilityWant = want;
W
wusongqing 已提交
201 202
    }

W
wusongqing 已提交
203
    onDestroy() {
204
        console.log("[Demo] EntryAbility onDestroy")
W
wusongqing 已提交
205
    }
W
wusongqing 已提交
206

W
wusongqing 已提交
207 208
    onWindowStageCreate(windowStage) {
        // Set the main page for this ability when the main window is created.
209
        console.log("[Demo] EntryAbility onWindowStageCreate")
W
wusongqing 已提交
210

W
wusongqing 已提交
211 212
        // Obtain AbilityContext and print the ability information.
        let context = this.context;
213
        console.log("[Demo] EntryAbility bundleName " + context.abilityInfo.bundleName)
W
wusongqing 已提交
214

215 216 217 218 219 220 221
        windowStage.loadContent("pages/index", (err, data) => {
            if (err.code) {
                console.error('Failed to load the content. Cause:' + JSON.stringify(err));
                return;
            }
            console.info('Succeeded in loading the content. Data: ' + JSON.stringify(data))
        });
W
wusongqing 已提交
222
    }
W
wusongqing 已提交
223

W
wusongqing 已提交
224 225
    onWindowStageDestroy() {
        // Release the UI related resources when the main window is destroyed.
226
        console.log("[Demo] EntryAbility onWindowStageDestroy")
W
wusongqing 已提交
227
    }
W
wusongqing 已提交
228

W
wusongqing 已提交
229 230
    onForeground() {
        // The ability is switched to run in the foreground.
231
        console.log("[Demo] EntryAbility onForeground")
W
wusongqing 已提交
232
    }
W
wusongqing 已提交
233

W
wusongqing 已提交
234 235
    onBackground() {
        // The ability is switched to run in the background.
236
        console.log("[Demo] EntryAbility onBackground")
W
wusongqing 已提交
237 238
    }
};
W
wusongqing 已提交
239 240 241 242
```

### application/FormExtensionContext

G
Gloria 已提交
243
For details, see [FormExtensionContext](../reference/apis/js-apis-inner-application-formExtensionContext.md).
W
wusongqing 已提交
244

L
liqiang 已提交
245
### Obtaining the Context on an ArkTS Page
W
wusongqing 已提交
246

247
In 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.
W
wusongqing 已提交
248 249 250

**How to Obtain**

L
liqiang 已提交
251
Use the API described in the table below to obtain the context associated with an ArkTS page.
W
wusongqing 已提交
252 253 254

| API                                  | Description                          |
| :------------------------------------ | :--------------------------- |
255
| getContext(component: Object): Object | Obtains the **Context** object associated with a component on the page.|
W
wusongqing 已提交
256 257 258 259

**Example**

```ts
260 261
// EntryAbility.ts
import UIAbility from '@ohos.app.ability.UIAbility';
W
wusongqing 已提交
262

263
export default class EntryAbility extends UIAbility {
W
wusongqing 已提交
264
    onCreate(want, launchParam) {
265
        console.log("[Demo] EntryAbility onCreate")
W
wusongqing 已提交
266 267 268
    }

    onDestroy() {
269
        console.log("[Demo] EntryAbility onDestroy")
W
wusongqing 已提交
270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286
    }

    onWindowStageCreate(windowStage) {
        // Load the index page and pass the current Context object.
        windowStage.setUIContent(this.context, "pages/index", null)
    }

    onWindowStageDestroy() {}

    onForeground() {}

    onBackground() {}
};
```

```ts
// pages/index.ets
287
import context from '@ohos.app.ability.context'
W
wusongqing 已提交
288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312

type Context = context.Context

@Entry
@Component
struct Index {
    build() {
        Row() {
            Column() {
                Text('GetContext')
                    .fontSize(50)
                    .fontWeight(FontWeight.Bold)
                    .onClick(() => {
                        // Obtain the Context object associated with the current component.
                        var context : Context = getContext(this) as Context
                        console.info("CacheDir:" + context.cacheDir)
                    })
            }
            .width('100%')
        }
        .height('100%')
    }
}
```

W
wusongqing 已提交
313
## Common Incorrect Usage
W
wusongqing 已提交
314

W
wusongqing 已提交
315
**Error 1: Use globalThis to obtain the context in the stage model.**
W
wusongqing 已提交
316 317 318 319

**Reason**

In 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.