stage-ability.md 16.8 KB
Newer Older
1 2
# Ability Development
## When to Use
G
Gloria 已提交
3
Ability development in the [stage model](stage-brief.md) is significantly different from that in the FA model. The stage model requires you to declare the application package structure in the `module.json5` and `app.json5` files during application development. For details about the configuration file, see [Application Package Structure Configuration File](../quick-start/stage-structure.md). To develop an ability based on the stage model, implement the following logic:
W
wusongqing 已提交
4
- Create an ability that supports screen viewing and human-machine interaction. You must implement the following scenarios: ability lifecycle callbacks, obtaining ability configuration, requesting permissions, and notifying environment changes.
W
wusongqing 已提交
5 6 7 8
- Start an ability. You need to implement ability startup on the same device, on a remote device, or with a specified UI page.
- Call abilities. For details, see [Call Development](stage-call.md).
- Connect to and disconnect from a Service Extension ability. For details, see [Service Extension Ability Development](stage-serviceextension.md).
- Continue the ability on another device. For details, see [Ability Continuation Development](stage-ability-continuation.md).
9 10

### Launch Type
G
Gloria 已提交
11
An ability can be launched in the **standard**, **singleton**, or **specified** mode, as configured by `launchType` in the `module.json5` file. Depending on the launch type, the action performed when the ability is started differs, as described below.
12

W
wusongqing 已提交
13
| Launch Type    | Description    |Action            |
14 15
| ----------- | -------  |---------------- |
| standard    | Multi-instance  | A new instance is started each time an ability starts.|
W
wusongqing 已提交
16
| singleton   | Singleton  | The ability has only one instance in the system. If an instance already exists when an ability is started, that instance is reused.|
17 18
| specified   | Instance-specific| The internal service of an ability determines whether to create multiple instances during running.|

G
Gloria 已提交
19
By default, the singleton mode is used. The following is an example of the `module.json5` file:
W
wusongqing 已提交
20 21 22 23 24 25 26 27 28 29 30 31 32 33
```json
{
  "module": {
    "abilities": [
      {
        "launchType": "singleton",
      }
    ]
  }
}
```
## Creating an Ability
### Available APIs
The table below describes the APIs provided by the `AbilityStage` class, which has the `context` attribute. For details about the APIs, see [AbilityStage](../reference/apis/js-apis-application-abilitystage.md).
34 35 36 37

**Table 1** AbilityStage APIs
|API|Description|
|:------|:------|
W
wusongqing 已提交
38 39 40
|onCreate(): void|Called when an ability stage is created.|
|onAcceptWant(want: Want): string|Called when a specified ability is started.|
|onConfigurationUpdated(config: Configuration): void|Called when the global configuration is updated.|
41

W
wusongqing 已提交
42
The table below describes the APIs provided by the `Ability` class. For details about the APIs, see [Ability](../reference/apis/js-apis-application-ability.md).
43 44

**Table 2** Ability APIs
G
Gloria 已提交
45

46 47
|API|Description|
|:------|:------|
W
wusongqing 已提交
48 49 50 51 52 53 54 55 56 57 58
|onCreate(want: Want, param: AbilityConstant.LaunchParam): void|Called when an ability is created.|
|onDestroy(): void|Called when the ability is destroyed.|
|onWindowStageCreate(windowStage: window.WindowStage): void|Called when a `WindowStage` is created for the ability. You can use the `window.WindowStage` APIs to implement operations such as page loading.|
|onWindowStageDestroy(): void|Called when the `WindowStage` is destroyed for the ability.|
|onForeground(): void|Called when the ability is switched to the foreground.|
|onBackground(): void|Called when the ability is switched to the background.|
|onNewWant(want: Want): void|Called when the ability launch type is set to `singleton`.|
|onConfigurationUpdated(config: Configuration): void|Called when the configuration of the environment where the ability is running is updated.|
### Implementing AbilityStage and Ability Lifecycle Callbacks
To create Page abilities for an application in the stage model, you must implement the `AbilityStage` class and ability lifecycle callbacks, and use the `Window` APIs to set the pages. The sample code is as follows:
1. Import the `AbilityStage` module.
59 60 61
   ```
   import AbilityStage from "@ohos.application.AbilityStage"
   ```
W
wusongqing 已提交
62
2. Implement the `AbilityStage` class. The default relative path generated by the APIs is **entry\src\main\ets\Application\AbilityStage.ts**.
63 64 65 66 67 68 69
   ```ts
   export default class MyAbilityStage extends AbilityStage {
    onCreate() {
        console.log("MyAbilityStage onCreate")
    }
   }
   ```
W
wusongqing 已提交
70
3. Import the `Ability` module.
71 72 73
   ```js
   import Ability from '@ohos.application.Ability'
   ```
W
wusongqing 已提交
74
4. Implement the lifecycle callbacks of the `Ability` class. The default relative path generated by the APIs is **entry\src\main\ets\MainAbility\MainAbility.ts**.
75

W
wusongqing 已提交
76
   In the `onWindowStageCreate(windowStage)` API, use `loadContent` to set the application page to be loaded. For details about how to use the `Window` APIs, see [Window Development](../windowmanager/window-guidelines.md).
77 78 79 80 81
   ```ts
   export default class MainAbility extends Ability {
    onCreate(want, launchParam) {
        console.log("MainAbility onCreate")
    }
W
wusongqing 已提交
82

83 84 85
    onDestroy() {
        console.log("MainAbility onDestroy")
    }
W
wusongqing 已提交
86

87 88
    onWindowStageCreate(windowStage) {
        console.log("MainAbility onWindowStageCreate")
W
wusongqing 已提交
89

W
wusongqing 已提交
90
        windowStage.loadContent("pages/index").then(() => {
W
wusongqing 已提交
91
            console.log("MainAbility load content succeed")
92 93 94 95
        }).catch((error) => {
            console.error("MainAbility load content failed with error: "+ JSON.stringify(error))
        })
    }
W
wusongqing 已提交
96

97 98 99
    onWindowStageDestroy() {
        console.log("MainAbility onWindowStageDestroy")
    }
W
wusongqing 已提交
100

101 102 103
    onForeground() {
        console.log("MainAbility onForeground")
    }
W
wusongqing 已提交
104

105 106 107 108 109
    onBackground() {
        console.log("MainAbility onBackground")
    }
   }
   ```
W
wusongqing 已提交
110
### Obtaining AbilityStage and Ability Configurations
G
Gloria 已提交
111 112 113 114
Both the `AbilityStage` and `Ability` classes have the `context` attribute. An application can obtain the context of an `Ability` instance through `this.context` to obtain the configuration details.

The following example shows how an application obtains the bundle code directory, HAP file name, ability name, and system language through the `context` attribute in the `AbilityStage` class. The sample code is as follows:

115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132
```ts
import AbilityStage from "@ohos.application.AbilityStage"
export default class MyAbilityStage extends AbilityStage {
    onCreate() {
        console.log("MyAbilityStage onCreate")
        let context = this.context
        console.log("MyAbilityStage bundleCodeDir" + context.bundleCodeDir)

        let currentHapModuleInfo = context.currentHapModuleInfo
        console.log("MyAbilityStage hap module name" + currentHapModuleInfo.name)
        console.log("MyAbilityStage hap module mainAbilityName" + currentHapModuleInfo.mainAbilityName)

        let config = this.context.config
        console.log("MyAbilityStage config language" + config.language)
    }
}
```

W
wusongqing 已提交
133
The following example shows how an application obtains the bundle code directory, HAP file name, ability name, and system language through the `context` attribute in the `Ability` class. The sample code is as follows:
134 135 136 137 138 139 140 141 142 143 144 145 146
```ts
import Ability from '@ohos.application.Ability'
export default class MainAbility extends Ability {
    onCreate(want, launchParam) {
        console.log("MainAbility onCreate")
        let context = this.context
        console.log("MainAbility bundleCodeDir" + context.bundleCodeDir)

        let abilityInfo = this.context.abilityInfo;
        console.log("MainAbility ability bundleName" + abilityInfo.bundleName)
        console.log("MainAbility ability name" + abilityInfo.name)

        let config = this.context.config
W
wusongqing 已提交
147
        console.log("MainAbility config language" + config.language)
148 149 150
    }
}
```
W
wusongqing 已提交
151
### Requesting Permissions
G
Gloria 已提交
152
If an application needs to obtain user privacy information or use system capabilities, for example, obtaining location information or using the camera to take photos or record videos, it must request the respective permission from consumers. During application development, you need to specify the involved sensitive permissions, declare the required permissions in `module.json5`, and use the `requestPermissionsFromUser` API to request the permission from consumers in the form of a dialog box. The following uses the permission for calendar access as an example.
153

G
Gloria 已提交
154
Declare the required permission in the `module.json5` file.
W
wusongqing 已提交
155 156 157 158 159 160 161
```json
"requestPermissions": [
    {
    "name": "ohos.permission.READ_CALENDAR"
    }
]
```
W
wusongqing 已提交
162
Request the permission from consumers in the form of a dialog box:
W
wusongqing 已提交
163 164 165 166 167 168 169 170 171 172
```ts
let context = this.context
let permissions: Array<string> = ['ohos.permission.READ_CALENDAR']
context.requestPermissionsFromUser(permissions).then((data) => {
    console.log("Succeed to request permission from user with data: " + JSON.stringify(data))
}).catch((error) => {
    console.log("Failed to request permission from user with error: " + JSON.stringify(error))
})
```
### Notifying of Environment Changes
W
wusongqing 已提交
173
Environment changes include changes of global configurations and ability configurations. Currently, the global configurations include the system language and color mode. The change of global configurations is generally triggered by configuration items in **Settings** or icons in **Control Panel**. The ability configuration is specific to a single `Ability` instance, including the display ID, screen resolution, and screen orientation. The configuration is related to the display where the ability is located, and the change is generally triggered by the window. For details on the configuration, see [Configuration](../reference/apis/js-apis-configuration.md).
W
wusongqing 已提交
174 175 176

For an application in the stage model, when the configuration changes, its abilities are not restarted, but the `onConfigurationUpdated(config: Configuration)` callback is triggered. If the application needs to perform processing based on the change, you can overwrite `onConfigurationUpdated`. Note that the `Configuration` object in the callback contains all the configurations of the current ability, not only the changed configurations.

W
wusongqing 已提交
177
The following example shows the implementation of the `onConfigurationUpdated` callback in the `AbilityStage` class. The callback is triggered when the system language and color mode are changed.  
W
wusongqing 已提交
178 179 180 181 182 183 184 185 186 187 188 189 190
```ts
import Ability from '@ohos.application.Ability'
import ConfigurationConstant from '@ohos.application.ConfigurationConstant'

export default class MyAbilityStage extends AbilityStage {
    onConfigurationUpdated(config) {
        if (config.colorMode === ConfigurationConstant.ColorMode.COLOR_MODE_DARK) {
            console.log('colorMode changed to dark')
        }
    }
}
```

W
wusongqing 已提交
191
The following example shows the implementation of the `onConfigurationUpdated` callback in the `Ability` class. The callback is triggered when the system language, color mode, or display parameters (such as the direction and density) change.  
W
wusongqing 已提交
192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211
```ts
import Ability from '@ohos.application.Ability'
import ConfigurationConstant from '@ohos.application.ConfigurationConstant'

export default class MainAbility extends Ability {
    direction : number;

    onCreate(want, launchParam) {
        this.direction = this.context.config.direction
    }

    onConfigurationUpdated(config) {
        if (this.direction !== config.direction) {
            console.log(`direction changed to ${config.direction}`)
        }
    }
}
```
## Starting an Ability
### Available APIs
W
wusongqing 已提交
212
The `Ability` class has the `context` attribute, which belongs to the `AbilityContext` class. The `AbilityContext` class has the `abilityInfo`, `currentHapModuleInfo`, and other attributes as well as the APIs used for starting abilities. For details, see [AbilityContext](../reference/apis/js-apis-ability-context.md).
W
wusongqing 已提交
213 214 215 216 217 218 219 220 221 222 223 224 225 226

**Table 3** AbilityContext APIs
|API|Description|
|:------|:------|
|startAbility(want: Want, callback: AsyncCallback\<void>): void|Starts an ability.|
|startAbility(want: Want, options?: StartOptions): Promise\<void>|Starts an ability.|
|startAbilityWithAccount(want: Want, accountId: number, callback: AsyncCallback\<void>): void|Starts an ability with the account ID.|
|startAbilityWithAccount(want: Want, accountId: number, options?: StartOptions): Promise\<void>|Starts an ability with the account ID.|
|startAbilityForResult(want: Want, callback: AsyncCallback\<AbilityResult>): void|Starts an ability with the returned result.|
|startAbilityForResult(want: Want, options?: StartOptions): Promise\<AbilityResult>|Starts an ability with the returned result.|
|startAbilityForResultWithAccount(want: Want, accountId: number, callback: AsyncCallback\<AbilityResult>): void|Starts an ability with the execution result and account ID.|
|startAbilityForResultWithAccount(want: Want, accountId: number, options?: StartOptions): Promise\<AbilityResult>|Starts an ability with the execution result and account ID.|
### Starting an Ability on the Same Device
An application can obtain the context of an `Ability` instance through `this.context` and then use the `startAbility` API in the `AbilityContext` class to start the ability. The ability can be started by specifying `Want`, `StartOptions`, and `accountId`, and the operation result can be returned using a callback or `Promise` instance. The sample code is as follows:
227 228 229 230 231 232 233
```ts
let context = this.context
var want = {
    "deviceId": "",
    "bundleName": "com.example.MyApplication",
    "abilityName": "MainAbility"
};
W
wusongqing 已提交
234 235
context.startAbility(want).then(() => {
    console.log("Succeed to start ability")
236 237 238 239 240
}).catch((error) => {
    console.error("Failed to start ability with error: "+ JSON.stringify(error))
})
```

W
wusongqing 已提交
241
### Starting an Ability on a Remote Device
W
wusongqing 已提交
242
>This feature applies only to system applications, since the `getTrustedDeviceListSync` API of the `DeviceManager` class is open only to system applications.
243 244 245 246 247 248 249 250
In the cross-device scenario, you must specify the ID of the remote device. The sample code is as follows:
```ts
let context = this.context
var want = {
    "deviceId": getRemoteDeviceId(),
    "bundleName": "com.example.MyApplication",
    "abilityName": "MainAbility"
};
W
wusongqing 已提交
251 252
context.startAbility(want).then(() => {
    console.log("Succeed to start remote ability")
253
}).catch((error) => {
W
wusongqing 已提交
254
    console.error("Failed to start remote ability with error: " + JSON.stringify(error))
255 256
})
```
W
wusongqing 已提交
257
Obtain the ID of a specified device from `DeviceManager`. The sample code is as follows:
258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273
```ts
import deviceManager from '@ohos.distributedHardware.deviceManager';
function getRemoteDeviceId() {
    if (typeof dmClass === 'object' && dmClass != null) {
        var list = dmClass.getTrustedDeviceListSync();
        if (typeof (list) == 'undefined' || typeof (list.length) == 'undefined') {
            console.log("MainAbility onButtonClick getRemoteDeviceId err: list is null");
            return;
        }
        console.log("MainAbility onButtonClick getRemoteDeviceId success:" + list[0].deviceId);
        return list[0].deviceId;
    } else {
        console.log("MainAbility onButtonClick getRemoteDeviceId err: dmClass is null");
    }
}
```
W
wusongqing 已提交
274
Request the permission `ohos.permission.DISTRIBUTED_DATASYNC` from consumers. This permission is used for data synchronization. For details about the sample code for requesting the permission, see [Requesting Permissions](##requesting-permissions).
W
wusongqing 已提交
275
### Starting an Ability with the Specified Page
G
Gloria 已提交
276
If the launch type of an ability is set to `singleton` and the ability has been started, the `onNewWant` callback is triggered when the ability is started again. You can pass start options through the `want`. For example, to start an ability with the specified page, use the `uri` or `parameters` parameter in the `want` to pass the page information. Currently, the ability in the stage model cannot directly use the `router` capability. You must pass the start options to the custom component and invoke the `router` method to display the specified page during the custom component lifecycle management. The sample code is as follows:
277

W
wusongqing 已提交
278
When using `startAbility` to start an ability again, use the `uri` parameter in the `want` to pass the page information.
279
```ts
W
wusongqing 已提交
280 281 282 283 284 285 286 287 288 289 290 291
async function reStartAbility() {
  try {
    await this.context.startAbility({
      bundleName: "com.sample.MyApplication",
      abilityName: "MainAbility",
      uri: "pages/second"
    })
    console.log('start ability succeed')
  } catch (error) {
    console.error(`start ability failed with ${error.code}`)
  }
}
292 293
```

W
wusongqing 已提交
294
Obtain the `want` parameter that contains the page information from the `onNewWant` callback of the ability.
295 296
```ts
import Ability from '@ohos.application.Ability'
W
wusongqing 已提交
297 298 299 300 301

export default class MainAbility extends Ability {
  onNewWant(want) {
    globalThis.newWant = want
  }
302 303 304
}
```

W
wusongqing 已提交
305
Obtain the `want` parameter that contains the page information from the custom component and process the route based on the URI.
306
```ts
W
wusongqing 已提交
307 308 309 310 311 312 313 314 315 316 317
import router from '@system.router'

@Entry
@Component
struct Index {
  newWant = undefined

  onPageShow() {
    console.info('Index onPageShow')
    let newWant = globalThis.newWant
    if (newWant.hasOwnProperty("uri")) {
W
wusongqing 已提交
318
      router.push({ url: newWant.uri });
W
wusongqing 已提交
319
      globalThis.newWant = undefined
320
    }
W
wusongqing 已提交
321
  }
322 323
}
```