context-userguide.md 12.1 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 
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
  
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 Ability from "@ohos.application.Ability";
W
wusongqing 已提交
101

W
wusongqing 已提交
102 103
var lifecycleid;

104
export default class MainAbility extends Ability {
W
wusongqing 已提交
105
    onCreate() {
106
        console.log("MainAbility 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
W
wusongqing 已提交
195 196
import Ability from '@ohos.application.Ability'

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

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

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

W
wusongqing 已提交
211 212 213
        // Obtain AbilityContext and print the ability information.
        let context = this.context;
        console.log("[Demo] MainAbility 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 226 227
    onWindowStageDestroy() {
        // Release the UI related resources when the main window is destroyed.
        console.log("[Demo] MainAbility onWindowStageDestroy")
    }
W
wusongqing 已提交
228

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

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

### application/FormExtensionContext

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

G
Gloria 已提交
253 254 255
| API                               | Description                                                        |
| :------------------------------------ | :----------------------------------------------------------- |
| 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.|
W
wusongqing 已提交
256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 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

**Example**

```ts
// MainAbility.ts
import Ability from '@ohos.application.Ability'

export default class MainAbility extends Ability {
    onCreate(want, launchParam) {
        console.log("[Demo] MainAbility onCreate")
    }

    onDestroy() {
        console.log("[Demo] MainAbility onDestroy")
    }

    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
import context from '@ohos.application.context'

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.