1# AppServiceExtensionContext (ExtensionAbility Context for Application Background Services) 2<!--Kit: Ability Kit--> 3<!--Subsystem: Ability--> 4<!--Owner: @yewei0794--> 5<!--Designer: @jsjzju--> 6<!--Tester: @lixueqing513--> 7<!--Adviser: @huipeizi--> 8 9The AppServiceExtensionContext module provides the context environment for the AppServiceExtensionAbility. It inherits from [ExtensionContext](js-apis-inner-application-extensionContext.md). 10 11AppServiceExtensionContext provides APIs to connect to and disconnect from a ServiceExtensionAbility (an ExtensionAbility for system application background services), as well as to terminate an AppServiceExtensionAbility. Note that a ServiceExtensionAbility can only be developed by system applications and supports connections from third-party applications. 12 13 14> **NOTE** 15> 16> - The initial APIs of this module are supported since API version 20. Newly added APIs will be marked with a superscript to indicate their earliest API version. 17> - The APIs of this module can be used only in the stage model. 18> - The APIs of this module must be used in the main thread, but not in child threads such as Worker and TaskPool. 19 20## Modules to Import 21 22```ts 23import { common } from '@kit.AbilityKit'; 24``` 25 26## Instructions 27 28Before using the AppServiceExtensionContext module, you must define a child class that inherits from AppServiceExtensionAbility. 29 30**Example** 31 32```ts 33import { AppServiceExtensionAbility } from '@kit.AbilityKit'; 34 35class AppServiceExtension extends AppServiceExtensionAbility { 36 onCreate() { 37 let context = this.context; // Obtain an AppServiceExtensionContext instance. 38 } 39} 40``` 41 42## AppServiceExtensionContext 43 44### startAbility 45 46startAbility(want: Want, options?: StartOptions): Promise<void> 47 48Starts an ability. This API can be called only by the main thread. It uses a promise to return the result. 49 50**System capability**: SystemCapability.Ability.AbilityRuntime.Core 51 52**Parameters** 53 54| Name| Type| Mandatory| Description| 55| -------- | -------- | -------- | -------- | 56| want | [Want](js-apis-app-ability-want.md) | Yes| Want information about the target ability, such as the ability name and bundle name.| 57| options | [StartOptions](js-apis-app-ability-startOptions.md) | No| Parameters used for starting the ability.| 58 59**Return value** 60 61| Type| Description| 62| -------- | -------- | 63| Promise<void> | Promise that returns no value.| 64 65**Error codes** 66 67For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Ability Error Codes](errorcode-ability.md). 68 69| ID| Error Message| 70| ------- | -------- | 71| 201 | The application does not have permission to call the interface. | 72| 16000001 | The specified ability does not exist. | 73| 16000002 | Incorrect ability type. | 74| 16000004 | Cannot start an invisible component. | 75| 16000005 | The specified process does not have the permission. | 76| 16000008 | The crowdtesting application expires. | 77| 16000009 | An ability cannot be started or stopped in Wukong mode. | 78| 16000010 | The call with the continuation and prepare continuation flag is forbidden. | 79| 16000011 | The context does not exist. | 80| 16000012 | The application is controlled. | 81| 16000013 | The application is controlled by EDM. | 82| 16000019 | No matching ability is found. | 83| 16000050 | Internal error. | 84| 16000055 | Installation-free timed out. | 85| 16000071 | App clone is not supported. | 86| 16000072 | App clone or multi-instance is not supported. | 87| 16000073 | The app clone index is invalid. | 88| 16000076 | The app instance key is invalid. | 89| 16000077 | The number of app instances reaches the limit. | 90| 16000078 | The multi-instance is not supported. | 91| 16000079 | The APP_INSTANCE_KEY cannot be specified. | 92| 16000080 | Creating a new instance is not supported. | 93 94**Example** 95 96```ts 97import { AppServiceExtensionAbility, Want, StartOptions } from '@kit.AbilityKit'; 98import { BusinessError } from '@kit.BasicServicesKit'; 99 100export default class MyAppServiceExtensionAbility extends AppServiceExtensionAbility { 101 onCreate(want: Want) { 102 let wantInfo: Want = { 103 bundleName: 'com.example.myapplication', 104 abilityName: 'EntryAbility' 105 }; 106 let options: StartOptions = { 107 displayId: 0 108 }; 109 110 try { 111 this.context.startAbility(wantInfo, options) 112 .then(() => { 113 // Carry out normal service processing. 114 console.info('startAbility succeed'); 115 }) 116 .catch((err: BusinessError) => { 117 // Process service logic errors. 118 console.error(`startAbility failed, code is ${err.code}, message is ${err.message}`); 119 }); 120 } catch (err) { 121 // Process input parameter errors. 122 let code = (err as BusinessError).code; 123 let message = (err as BusinessError).message; 124 console.error(`startAbility failed, code is ${code}, message is ${message}`); 125 } 126 } 127} 128``` 129 130### connectServiceExtensionAbility 131 132connectServiceExtensionAbility(want: Want, callback: ConnectOptions): number 133 134Connects this AppServiceExtensionAbility to a ServiceExtensionAbility. It enables communication with the ServiceExtensionAbility via a proxy, allowing access to the capabilities exposed by the ServiceExtensionAbility. This API can be called only by the main thread. 135 136**System capability**: SystemCapability.Ability.AbilityRuntime.Core 137 138**Parameters** 139 140| Name| Type| Mandatory| Description| 141| -------- | -------- | -------- | -------- | 142| want | [Want](js-apis-app-ability-want.md) | Yes| Want information about the target ability, such as the ability name and bundle name.| 143| callback | [ConnectOptions](js-apis-inner-ability-connectOptions.md) | Yes| Callback used to return the information indicating that the connection is successful, failed, or interrupted.| 144 145**Return value** 146 147| Type| Description| 148| -------- | -------- | 149| number | Connection ID. The client can call [disconnectServiceExtensionAbility](#disconnectserviceextensionability) with this ID for disconnection.| 150 151**Error codes** 152 153For details about the error codes, see [Ability Error Codes](errorcode-ability.md). 154 155| ID| Error Message| 156| ------- | -------- | 157| 16000001 | The specified ability does not exist. | 158| 16000002 | Incorrect ability type. | 159| 16000004 | Cannot start an invisible component. | 160| 16000005 | The specified process does not have the permission. | 161| 16000006 | Cross-user operations are not allowed. | 162| 16000008 | The crowdtesting application expires. | 163| 16000011 | The context does not exist. | 164| 16000050 | Internal error. | 165 166**Example** 167 168```ts 169import { AppServiceExtensionAbility, Want, common } from '@kit.AbilityKit'; 170import { rpc } from '@kit.IPCKit'; 171import { BusinessError } from '@kit.BasicServicesKit'; 172import { hilog } from '@kit.PerformanceAnalysisKit'; 173 174let commRemote: rpc.IRemoteObject; // Release the instance when the connection is disconnected. 175const TAG: string = '[AppServiceExtensionAbility]'; 176 177class AppServiceExtension extends AppServiceExtensionAbility { 178 onCreate() { 179 let want: Want = { 180 bundleName: 'com.example.myapp', 181 abilityName: 'MyAbility' 182 }; 183 let callback: common.ConnectOptions = { 184 onConnect(elementName, remote) { 185 commRemote = remote; 186 hilog.info(0x0000, TAG, '----------- onConnect -----------'); 187 }, 188 onDisconnect(elementName) { 189 hilog.info(0x0000, TAG, '----------- onDisconnect -----------'); 190 }, 191 onFailed(code) { 192 hilog.error(0x0000, TAG, '----------- onFailed -----------'); 193 } 194 }; 195 let connection: number; 196 197 try { 198 connection = this.context.connectServiceExtensionAbility(want, callback); 199 } catch (paramError) { 200 // Process input parameter errors. 201 hilog.error(0x0000, TAG, `error.code: ${(paramError as BusinessError).code}, error.message: ${(paramError as BusinessError).message}`); 202 } 203 } 204} 205``` 206 207### disconnectServiceExtensionAbility 208 209disconnectServiceExtensionAbility(connection: number): Promise<void> 210 211Disconnects this AppServiceExtensionAbility from a ServiceExtensionAbility. This API can be called only by the main thread. It uses a promise to return the result. 212 213**System capability**: SystemCapability.Ability.AbilityRuntime.Core 214 215**Parameters** 216 217| Name| Type| Mandatory| Description| 218| -------- | -------- | -------- | -------- | 219| connection | number | Yes| Connection ID returned by [connectServiceExtensionAbility](#connectserviceextensionability).| 220 221**Return value** 222 223| Type| Description| 224| -------- | -------- | 225| Promise<void> | Promise that returns no value.| 226 227**Error codes** 228 229For details about the error codes, see [Ability Error Codes](errorcode-ability.md). 230 231| ID| Error Message| 232| ------- | -------- | 233| 16000011 | The context does not exist. | 234| 16000050 | Internal error. | 235 236**Example** 237 238```ts 239import { AppServiceExtensionAbility } from '@kit.AbilityKit'; 240import { rpc } from '@kit.IPCKit'; 241import { BusinessError } from '@kit.BasicServicesKit'; 242import { hilog } from '@kit.PerformanceAnalysisKit'; 243 244let commRemote: rpc.IRemoteObject | null; // Release the instance when the connection is disconnected. 245const TAG: string = '[AppServiceExtensionAbility]'; 246 247class AppServiceExtension extends AppServiceExtensionAbility { 248 onCreate() { 249 // connection is the return value of connectServiceExtensionAbility. 250 let connection = 1; 251 try { 252 this.context.disconnectServiceExtensionAbility(connection) 253 .then(() => { 254 commRemote = null; 255 // Carry out normal service processing. 256 hilog.info(0x0000, TAG, '----------- disconnectServiceExtensionAbility success -----------'); 257 }) 258 .catch((error: BusinessError) => { 259 commRemote = null; 260 // Process service logic errors. 261 hilog.error(0x0000, TAG, `disconnectServiceExtensionAbility failed, error.code: ${error.code}, error.message: ${error.message}`); 262 }); 263 } catch (paramError) { 264 commRemote = null; 265 // Process input parameter errors. 266 hilog.error(0x0000, TAG, `error.code: ${(paramError as BusinessError).code}, error.message: ${(paramError as BusinessError).message}`); 267 } 268 } 269} 270``` 271 272### terminateSelf 273 274terminateSelf(): Promise<void> 275 276Terminates this AppServiceExtensionAbility. This API can be called only by the main thread. It uses a promise to return the result. 277 278**System capability**: SystemCapability.Ability.AbilityRuntime.Core 279 280**Return value** 281 282| Type| Description| 283| -------- | -------- | 284| Promise<void> | Promise that returns no value.| 285 286**Error codes** 287 288For details about the error codes, see [Ability Error Codes](errorcode-ability.md). 289 290| ID| Error Message| 291| ------- | -------------------------------- | 292| 16000009 | An ability cannot be started or stopped in Wukong mode. | 293| 16000011 | The context does not exist. | 294| 16000050 | Internal error. | 295 296**Example** 297 298```ts 299import { AppServiceExtensionAbility } from '@kit.AbilityKit'; 300import { BusinessError } from '@kit.BasicServicesKit'; 301import { hilog } from '@kit.PerformanceAnalysisKit'; 302 303const TAG: string = '[AppServiceExtensionAbility]'; 304 305class AppServiceExtension extends AppServiceExtensionAbility { 306 onCreate() { 307 this.context.terminateSelf().then(() => { 308 // Carry out normal service processing. 309 hilog.info(0x0000, TAG, '----------- terminateSelf succeed -----------'); 310 }).catch((error: BusinessError) => { 311 // Process service logic errors. 312 hilog.error(0x0000, TAG, `terminateSelf failed, error.code: ${error.code}, error.message: ${error.message}`); 313 }); 314 } 315} 316``` 317