• 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/application-package-structure-stage.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| multiton    | Multi-instance mode| A new instance is started each time an ability starts.|
16| singleton   | Singleton mode  | 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-app-ability-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, launchParams: AbilityConstant.LaunchParam): 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** class 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 **UIAbility** class. The default relative path generated by the APIs is **entry\src\main\ets\entryability\EntryAbility.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/application-window-stage.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"
117
118export default class MyAbilityStage extends AbilityStage {
119    onCreate() {
120        console.log("MyAbilityStage onCreate")
121        let context = this.context
122        console.log("MyAbilityStage bundleCodeDir" + context.bundleCodeDir)
123
124        let currentHapModuleInfo = context.currentHapModuleInfo
125        console.log("MyAbilityStage hap module name" + currentHapModuleInfo.name)
126        console.log("MyAbilityStage hap module mainAbilityName" + currentHapModuleInfo.mainAbilityName)
127
128        let config = this.context.config
129        console.log("MyAbilityStage config language" + config.language)
130    }
131}
132```
133
134The 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:
135```ts
136import Ability from '@ohos.application.Ability'
137export default class MainAbility extends Ability {
138    onCreate(want, launchParam) {
139        console.log("MainAbility onCreate")
140        let context = this.context
141        console.log("MainAbility bundleCodeDir" + context.bundleCodeDir)
142
143        let abilityInfo = this.context.abilityInfo;
144        console.log("MainAbility ability bundleName" + abilityInfo.bundleName)
145        console.log("MainAbility ability name" + abilityInfo.name)
146
147        let config = this.context.config
148        console.log("MainAbility config language" + config.language)
149    }
150}
151```
152### Notifying of Environment Changes
153Environment 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. Before configuring a project, define the project in the [Configuration](../reference/apis/js-apis-application-configuration.md) class.
154
155For 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 override **onConfigurationUpdated**. Note that the **Configuration** object in the callback contains all the configurations of the current ability, not only the changed configurations.
156
157The 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.
158```ts
159import AbilityStage from '@ohos.application.AbilityStage'
160import ConfigurationConstant from '@ohos.application.ConfigurationConstant'
161
162export default class MyAbilityStage extends AbilityStage {
163    onConfigurationUpdated(config) {
164        if (config.colorMode === ConfigurationConstant.ColorMode.COLOR_MODE_DARK) {
165            console.log('colorMode changed to dark')
166        }
167    }
168}
169```
170
171The 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.
172```ts
173import Ability from '@ohos.application.Ability'
174import ConfigurationConstant from '@ohos.application.ConfigurationConstant'
175
176export default class MainAbility extends Ability {
177    direction : number;
178
179    onCreate(want, launchParam) {
180        this.direction = this.context.config.direction
181    }
182
183    onConfigurationUpdated(config) {
184        if (this.direction !== config.direction) {
185            console.log(`direction changed to ${config.direction}`)
186        }
187    }
188}
189```
190## Starting an Ability
191### Available APIs
192The **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-inner-application-applicationContext.md).
193
194**Table 3** AbilityContext APIs
195|API|Description|
196|:------|:------|
197|startAbility(want: Want, callback: AsyncCallback\<void>): void|Starts an ability.|
198|startAbility(want: Want, options?: StartOptions): Promise\<void>|Starts an ability.|
199|startAbilityWithAccount(want: Want, accountId: number, callback: AsyncCallback\<void>): void|Starts an ability with the account ID.|
200|startAbilityWithAccount(want: Want, accountId: number, options?: StartOptions): Promise\<void>|Starts an ability with the account ID.|
201|startAbilityForResult(want: Want, callback: AsyncCallback\<AbilityResult>): void|Starts an ability with the returned result.|
202|startAbilityForResult(want: Want, options?: StartOptions): Promise\<AbilityResult>|Starts an ability with the returned result.|
203|startAbilityForResultWithAccount(want: Want, accountId: number, callback: AsyncCallback\<AbilityResult>): void|Starts an ability with the execution result and account ID.|
204|startAbilityForResultWithAccount(want: Want, accountId: number, options?: StartOptions): Promise\<AbilityResult>|Starts an ability with the execution result and account ID.|
205### Starting an Ability on the Same Device
206An 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:
207```ts
208let context = this.context
209var want = {
210    "deviceId": "",
211    "bundleName": "com.example.MyApplication",
212    "abilityName": "MainAbility"
213};
214context.startAbility(want).then(() => {
215    console.log("Succeed to start ability")
216}).catch((error) => {
217    console.error("Failed to start ability with error: "+ JSON.stringify(error))
218})
219```
220
221### Starting an Ability on a Remote Device
222>This feature applies only to system applications, since the **getTrustedDeviceListSync** API of the **DeviceManager** class is open only to system applications.
223In the cross-device scenario, you must specify the ID of the remote device. The sample code is as follows:
224```ts
225let context = this.context
226var want = {
227    "deviceId": getRemoteDeviceId(),
228    "bundleName": "com.example.MyApplication",
229    "abilityName": "MainAbility"
230};
231context.startAbility(want).then(() => {
232    console.log("Succeed to start remote ability")
233}).catch((error) => {
234    console.error("Failed to start remote ability with error: " + JSON.stringify(error))
235})
236```
237Obtain the ID of a specified device from **DeviceManager**. The sample code is as follows:
238```ts
239import deviceManager from '@ohos.distributedHardware.deviceManager';
240function getRemoteDeviceId() {
241    if (typeof dmClass === 'object' && dmClass != null) {
242        var list = dmClass.getTrustedDeviceListSync();
243        if (typeof (list) == 'undefined' || typeof (list.length) == 'undefined') {
244            console.log("MainAbility onButtonClick getRemoteDeviceId err: list is null");
245            return;
246        }
247        console.log("MainAbility onButtonClick getRemoteDeviceId success:" + list[0].deviceId);
248        return list[0].deviceId;
249    } else {
250        console.log("MainAbility onButtonClick getRemoteDeviceId err: dmClass is null");
251    }
252}
253```
254Request the permission **ohos.permission.DISTRIBUTED_DATASYNC** from consumers. This permission is used for data synchronization. For details about the sample code for requesting permissions, see [abilityAccessCtrl.requestPermissionsFromUse](../reference/apis/js-apis-abilityAccessCtrl.md#requestpermissionsfromuser9).
255### Starting an Ability with the Specified Page
256If 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:
257
258When using **startAbility** to start an ability again, use the **uri** parameter in the **want** to pass the page information.
259```ts
260async function reStartAbility() {
261  try {
262    await this.context.startAbility({
263      bundleName: "com.sample.MyApplication",
264      abilityName: "MainAbility",
265      uri: "pages/second"
266    })
267    console.log('start ability succeed')
268  } catch (error) {
269    console.error(`start ability failed with ${error.code}`)
270  }
271}
272```
273
274Obtain the **want** parameter that contains the page information from the **onNewWant** callback of the ability.
275```ts
276import Ability from '@ohos.application.Ability'
277
278export default class MainAbility extends Ability {
279  onNewWant(want, launchParams) {
280    globalThis.newWant = want
281  }
282}
283```
284
285Obtain the **want** parameter that contains the page information from the custom component and process the route based on the URI.
286```ts
287import router from '@ohos.router'
288
289@Entry
290@Component
291struct Index {
292  newWant = undefined
293
294  onPageShow() {
295    console.info('Index onPageShow')
296    let newWant = globalThis.newWant
297    if (newWant.hasOwnProperty("uri")) {
298      router.push({ url: newWant.uri });
299      globalThis.newWant = undefined
300    }
301  }
302}
303```
304