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| standard | Standard 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\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/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" 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### Notifying of Environment Changes 152Environment 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. 153 154For 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. 155 156The 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. 157```ts 158import AbilityStage from '@ohos.application.AbilityStage' 159import ConfigurationConstant from '@ohos.application.ConfigurationConstant' 160 161export default class MyAbilityStage extends AbilityStage { 162 onConfigurationUpdated(config) { 163 if (config.colorMode === ConfigurationConstant.ColorMode.COLOR_MODE_DARK) { 164 console.log('colorMode changed to dark') 165 } 166 } 167} 168``` 169 170The 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. 171```ts 172import Ability from '@ohos.application.Ability' 173import ConfigurationConstant from '@ohos.application.ConfigurationConstant' 174 175export default class MainAbility extends Ability { 176 direction : number; 177 178 onCreate(want, launchParam) { 179 this.direction = this.context.config.direction 180 } 181 182 onConfigurationUpdated(config) { 183 if (this.direction !== config.direction) { 184 console.log(`direction changed to ${config.direction}`) 185 } 186 } 187} 188``` 189## Starting an Ability 190### Available APIs 191The **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). 192 193**Table 3** AbilityContext APIs 194|API|Description| 195|:------|:------| 196|startAbility(want: Want, callback: AsyncCallback\<void>): void|Starts an ability.| 197|startAbility(want: Want, options?: StartOptions): Promise\<void>|Starts an ability.| 198|startAbilityWithAccount(want: Want, accountId: number, callback: AsyncCallback\<void>): void|Starts an ability with the account ID.| 199|startAbilityWithAccount(want: Want, accountId: number, options?: StartOptions): Promise\<void>|Starts an ability with the account ID.| 200|startAbilityForResult(want: Want, callback: AsyncCallback\<AbilityResult>): void|Starts an ability with the returned result.| 201|startAbilityForResult(want: Want, options?: StartOptions): Promise\<AbilityResult>|Starts an ability with the returned result.| 202|startAbilityForResultWithAccount(want: Want, accountId: number, callback: AsyncCallback\<AbilityResult>): void|Starts an ability with the execution result and account ID.| 203|startAbilityForResultWithAccount(want: Want, accountId: number, options?: StartOptions): Promise\<AbilityResult>|Starts an ability with the execution result and account ID.| 204### Starting an Ability on the Same Device 205An 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: 206```ts 207let context = this.context 208var want = { 209 "deviceId": "", 210 "bundleName": "com.example.MyApplication", 211 "abilityName": "MainAbility" 212}; 213context.startAbility(want).then(() => { 214 console.log("Succeed to start ability") 215}).catch((error) => { 216 console.error("Failed to start ability with error: "+ JSON.stringify(error)) 217}) 218``` 219 220### Starting an Ability on a Remote Device 221>This feature applies only to system applications, since the **getTrustedDeviceListSync** API of the **DeviceManager** class is open only to system applications. 222In the cross-device scenario, you must specify the ID of the remote device. The sample code is as follows: 223```ts 224let context = this.context 225var want = { 226 "deviceId": getRemoteDeviceId(), 227 "bundleName": "com.example.MyApplication", 228 "abilityName": "MainAbility" 229}; 230context.startAbility(want).then(() => { 231 console.log("Succeed to start remote ability") 232}).catch((error) => { 233 console.error("Failed to start remote ability with error: " + JSON.stringify(error)) 234}) 235``` 236Obtain the ID of a specified device from **DeviceManager**. The sample code is as follows: 237```ts 238import deviceManager from '@ohos.distributedHardware.deviceManager'; 239function getRemoteDeviceId() { 240 if (typeof dmClass === 'object' && dmClass != null) { 241 var list = dmClass.getTrustedDeviceListSync(); 242 if (typeof (list) == 'undefined' || typeof (list.length) == 'undefined') { 243 console.log("MainAbility onButtonClick getRemoteDeviceId err: list is null"); 244 return; 245 } 246 console.log("MainAbility onButtonClick getRemoteDeviceId success:" + list[0].deviceId); 247 return list[0].deviceId; 248 } else { 249 console.log("MainAbility onButtonClick getRemoteDeviceId err: dmClass is null"); 250 } 251} 252``` 253Request 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). 254### Starting an Ability with the Specified Page 255If 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: 256 257When using **startAbility** to start an ability again, use the **uri** parameter in the **want** to pass the page information. 258```ts 259async function reStartAbility() { 260 try { 261 await this.context.startAbility({ 262 bundleName: "com.sample.MyApplication", 263 abilityName: "MainAbility", 264 uri: "pages/second" 265 }) 266 console.log('start ability succeed') 267 } catch (error) { 268 console.error(`start ability failed with ${error.code}`) 269 } 270} 271``` 272 273Obtain the **want** parameter that contains the page information from the **onNewWant** callback of the ability. 274```ts 275import Ability from '@ohos.application.Ability' 276 277export default class MainAbility extends Ability { 278 onNewWant(want, launchParams) { 279 globalThis.newWant = want 280 } 281} 282``` 283 284Obtain the **want** parameter that contains the page information from the custom component and process the route based on the URI. 285```ts 286import router from '@ohos.router' 287 288@Entry 289@Component 290struct Index { 291 newWant = undefined 292 293 onPageShow() { 294 console.info('Index onPageShow') 295 let newWant = globalThis.newWant 296 if (newWant.hasOwnProperty("uri")) { 297 router.push({ url: newWant.uri }); 298 globalThis.newWant = undefined 299 } 300 } 301} 302``` 303