• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Ability Development
2## When to Use
3Ability 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:
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.
5- Start an ability. You need to implement ability startup on the same device, on a remote device, or with a specified UI page.
6- Call abilities. For details, see [Call Development](stage-call.md).
7- Connect to and disconnect from a Service Extension ability. For details, see [Service Extension Ability Development](stage-serviceextension.md).
8- Continue the ability on another device. For details, see [Ability Continuation Development](stage-ability-continuation.md).
9
10### Launch Type
11An 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
13| Launch Type    | Description    |Action            |
14| ----------- | -------  |---------------- |
15| standard    | Multi-instance  | A new instance is started each time an ability starts.|
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| specified   | Instance-specific| The internal service of an ability determines whether to create multiple instances during running.|
18
19By default, the singleton mode is used. The following is an example of the `module.json5` file:
20```json
21{
22  "module": {
23    "abilities": [
24      {
25        "launchType": "singleton",
26      }
27    ]
28  }
29}
30```
31## Creating an Ability
32### Available APIs
33The 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**Table 1** AbilityStage APIs
36|API|Description|
37|:------|:------|
38|onCreate(): void|Called when an ability stage is created.|
39|onAcceptWant(want: Want): string|Called when a specified ability is started.|
40|onConfigurationUpdated(config: Configuration): void|Called when the global configuration is updated.|
41
42The 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
45
46|API|Description|
47|:------|:------|
48|onCreate(want: Want, param: AbilityConstant.LaunchParam): void|Called when an ability is created.|
49|onDestroy(): void|Called when the ability is destroyed.|
50|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.|
51|onWindowStageDestroy(): void|Called when the `WindowStage` is destroyed for the ability.|
52|onForeground(): void|Called when the ability is switched to the foreground.|
53|onBackground(): void|Called when the ability is switched to the background.|
54|onNewWant(want: Want): void|Called when the ability launch type is set to `singleton`.|
55|onConfigurationUpdated(config: Configuration): void|Called when the configuration of the environment where the ability is running is updated.|
56### Implementing AbilityStage and Ability Lifecycle Callbacks
57To 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:
581. Import the `AbilityStage` module.
59   ```
60   import AbilityStage from "@ohos.application.AbilityStage"
61   ```
622. Implement the `AbilityStage` class. The default relative path generated by the APIs is **entry\src\main\ets\Application\AbilityStage.ts**.
63   ```ts
64   export default class MyAbilityStage extends AbilityStage {
65    onCreate() {
66        console.log("MyAbilityStage onCreate")
67    }
68   }
69   ```
703. Import the `Ability` module.
71   ```js
72   import Ability from '@ohos.application.Ability'
73   ```
744. 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
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   ```ts
78   export default class MainAbility extends Ability {
79    onCreate(want, launchParam) {
80        console.log("MainAbility onCreate")
81    }
82
83    onDestroy() {
84        console.log("MainAbility onDestroy")
85    }
86
87    onWindowStageCreate(windowStage) {
88        console.log("MainAbility onWindowStageCreate")
89
90        windowStage.loadContent("pages/index").then(() => {
91            console.log("MainAbility load content succeed")
92        }).catch((error) => {
93            console.error("MainAbility load content failed with error: "+ JSON.stringify(error))
94        })
95    }
96
97    onWindowStageDestroy() {
98        console.log("MainAbility onWindowStageDestroy")
99    }
100
101    onForeground() {
102        console.log("MainAbility onForeground")
103    }
104
105    onBackground() {
106        console.log("MainAbility onBackground")
107    }
108   }
109   ```
110### Obtaining AbilityStage and Ability Configurations
111Both 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.
112
113The 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:
114
115```ts
116import AbilityStage from "@ohos.application.AbilityStage"
117export default class MyAbilityStage extends AbilityStage {
118    onCreate() {
119        console.log("MyAbilityStage onCreate")
120        let context = this.context
121        console.log("MyAbilityStage bundleCodeDir" + context.bundleCodeDir)
122
123        let currentHapModuleInfo = context.currentHapModuleInfo
124        console.log("MyAbilityStage hap module name" + currentHapModuleInfo.name)
125        console.log("MyAbilityStage hap module mainAbilityName" + currentHapModuleInfo.mainAbilityName)
126
127        let config = this.context.config
128        console.log("MyAbilityStage config language" + config.language)
129    }
130}
131```
132
133The 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```ts
135import Ability from '@ohos.application.Ability'
136export default class MainAbility extends Ability {
137    onCreate(want, launchParam) {
138        console.log("MainAbility onCreate")
139        let context = this.context
140        console.log("MainAbility bundleCodeDir" + context.bundleCodeDir)
141
142        let abilityInfo = this.context.abilityInfo;
143        console.log("MainAbility ability bundleName" + abilityInfo.bundleName)
144        console.log("MainAbility ability name" + abilityInfo.name)
145
146        let config = this.context.config
147        console.log("MainAbility config language" + config.language)
148    }
149}
150```
151### Requesting Permissions
152If 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
154Declare the required permission in the `module.json5` file.
155```json
156"requestPermissions": [
157    {
158    "name": "ohos.permission.READ_CALENDAR"
159    }
160]
161```
162Request the permission from consumers in the form of a dialog box:
163```ts
164let context = this.context
165let permissions: Array<string> = ['ohos.permission.READ_CALENDAR']
166context.requestPermissionsFromUser(permissions).then((data) => {
167    console.log("Succeed to request permission from user with data: " + JSON.stringify(data))
168}).catch((error) => {
169    console.log("Failed to request permission from user with error: " + JSON.stringify(error))
170})
171```
172### Notifying of Environment Changes
173Environment 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).
174
175For 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.
176
177The 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.
178```ts
179import Ability from '@ohos.application.Ability'
180import ConfigurationConstant from '@ohos.application.ConfigurationConstant'
181
182export default class MyAbilityStage extends AbilityStage {
183    onConfigurationUpdated(config) {
184        if (config.colorMode === ConfigurationConstant.ColorMode.COLOR_MODE_DARK) {
185            console.log('colorMode changed to dark')
186        }
187    }
188}
189```
190
191The 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.
192```ts
193import Ability from '@ohos.application.Ability'
194import ConfigurationConstant from '@ohos.application.ConfigurationConstant'
195
196export default class MainAbility extends Ability {
197    direction : number;
198
199    onCreate(want, launchParam) {
200        this.direction = this.context.config.direction
201    }
202
203    onConfigurationUpdated(config) {
204        if (this.direction !== config.direction) {
205            console.log(`direction changed to ${config.direction}`)
206        }
207    }
208}
209```
210## Starting an Ability
211### Available APIs
212The `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).
213
214**Table 3** AbilityContext APIs
215|API|Description|
216|:------|:------|
217|startAbility(want: Want, callback: AsyncCallback\<void>): void|Starts an ability.|
218|startAbility(want: Want, options?: StartOptions): Promise\<void>|Starts an ability.|
219|startAbilityWithAccount(want: Want, accountId: number, callback: AsyncCallback\<void>): void|Starts an ability with the account ID.|
220|startAbilityWithAccount(want: Want, accountId: number, options?: StartOptions): Promise\<void>|Starts an ability with the account ID.|
221|startAbilityForResult(want: Want, callback: AsyncCallback\<AbilityResult>): void|Starts an ability with the returned result.|
222|startAbilityForResult(want: Want, options?: StartOptions): Promise\<AbilityResult>|Starts an ability with the returned result.|
223|startAbilityForResultWithAccount(want: Want, accountId: number, callback: AsyncCallback\<AbilityResult>): void|Starts an ability with the execution result and account ID.|
224|startAbilityForResultWithAccount(want: Want, accountId: number, options?: StartOptions): Promise\<AbilityResult>|Starts an ability with the execution result and account ID.|
225### Starting an Ability on the Same Device
226An 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```ts
228let context = this.context
229var want = {
230    "deviceId": "",
231    "bundleName": "com.example.MyApplication",
232    "abilityName": "MainAbility"
233};
234context.startAbility(want).then(() => {
235    console.log("Succeed to start ability")
236}).catch((error) => {
237    console.error("Failed to start ability with error: "+ JSON.stringify(error))
238})
239```
240
241### Starting an Ability on a Remote Device
242>This feature applies only to system applications, since the `getTrustedDeviceListSync` API of the `DeviceManager` class is open only to system applications.
243In the cross-device scenario, you must specify the ID of the remote device. The sample code is as follows:
244```ts
245let context = this.context
246var want = {
247    "deviceId": getRemoteDeviceId(),
248    "bundleName": "com.example.MyApplication",
249    "abilityName": "MainAbility"
250};
251context.startAbility(want).then(() => {
252    console.log("Succeed to start remote ability")
253}).catch((error) => {
254    console.error("Failed to start remote ability with error: " + JSON.stringify(error))
255})
256```
257Obtain the ID of a specified device from `DeviceManager`. The sample code is as follows:
258```ts
259import deviceManager from '@ohos.distributedHardware.deviceManager';
260function getRemoteDeviceId() {
261    if (typeof dmClass === 'object' && dmClass != null) {
262        var list = dmClass.getTrustedDeviceListSync();
263        if (typeof (list) == 'undefined' || typeof (list.length) == 'undefined') {
264            console.log("MainAbility onButtonClick getRemoteDeviceId err: list is null");
265            return;
266        }
267        console.log("MainAbility onButtonClick getRemoteDeviceId success:" + list[0].deviceId);
268        return list[0].deviceId;
269    } else {
270        console.log("MainAbility onButtonClick getRemoteDeviceId err: dmClass is null");
271    }
272}
273```
274Request 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).
275### Starting an Ability with the Specified Page
276If 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
278When using `startAbility` to start an ability again, use the `uri` parameter in the `want` to pass the page information.
279```ts
280async function reStartAbility() {
281  try {
282    await this.context.startAbility({
283      bundleName: "com.sample.MyApplication",
284      abilityName: "MainAbility",
285      uri: "pages/second"
286    })
287    console.log('start ability succeed')
288  } catch (error) {
289    console.error(`start ability failed with ${error.code}`)
290  }
291}
292```
293
294Obtain the `want` parameter that contains the page information from the `onNewWant` callback of the ability.
295```ts
296import Ability from '@ohos.application.Ability'
297
298export default class MainAbility extends Ability {
299  onNewWant(want) {
300    globalThis.newWant = want
301  }
302}
303```
304
305Obtain the `want` parameter that contains the page information from the custom component and process the route based on the URI.
306```ts
307import router from '@system.router'
308
309@Entry
310@Component
311struct Index {
312  newWant = undefined
313
314  onPageShow() {
315    console.info('Index onPageShow')
316    let newWant = globalThis.newWant
317    if (newWant.hasOwnProperty("uri")) {
318      router.push({ url: newWant.uri });
319      globalThis.newWant = undefined
320    }
321  }
322}
323```
324