1# ServiceExtensionAbility 2 3## Overview 4 5[ServiceExtensionAbility](../reference/apis/js-apis-app-ability-serviceExtensionAbility.md) is an ExtensionAbility component of the SERVICE type that provides capabilities related to background services. It holds an internal [ServiceExtensionContext](../reference/apis/js-apis-inner-application-serviceExtensionContext.md), through which a variety of APIs are provided for external systems. 6 7In this document, the started ServiceExtensionAbility component is called the server, and the component that starts ServiceExtensionAbility is called the client. 8 9A ServiceExtensionAbility can be started or connected by other components to process transactions in the background based on the request of the caller. System applications can call the [startServiceExtensionAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartserviceextensionability) method to start background services or call the [connectServiceExtensionAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextconnectserviceextensionability) method to connect to background services. Third-party applications can call only **connectServiceExtensionAbility()** to connect to background services. The differences between starting and connecting to background services are as follows: 10 11- **Starting**: In the case that AbilityA starts ServiceB, they are weakly associated. After AbilityA exits, ServiceB can still exist. 12 13- **Connecting**: In the case that AbilityA connects to ServiceB, they are strongly associated. After AbilityA exits, ServiceB also exits. 14 15Note the following: 16 17- If a ServiceExtensionAbility is started only by means of connecting, its lifecycle is controlled by the client. A new connection is set up each time the client calls the [connectServiceExtensionAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextconnectserviceextensionability) method. When the client exits or calls the [disconnectServiceExtensionAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextdisconnectserviceextensionability) method, the connection is disconnected. After all connections are disconnected, the ServiceExtensionAbility automatically exits. 18 19- Once a ServiceExtensionAbility is started by means of starting, it will not exit automatically. System applications can call the [stopServiceExtensionAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstopserviceextensionability) method to stop it. 20 21> **NOTE** 22> 23> - Currently, third-party applications cannot implement ServiceExtensionAbility. If you want to implement transaction processing in the background, use background tasks. For details, see [Background Task](../task-management/background-task-overview.md). 24> - UIAbility of a third-party application can connect to ServiceExtensionAbility provided by the system through the context. 25> - Third-party applications can connect to ServiceExtensionAbility provided by the system only when they gain focus in the foreground. 26 27## Lifecycle 28 29[ServiceExtensionAbility](../reference/apis/js-apis-app-ability-serviceExtensionAbility.md) provides the callbacks **onCreate()**, **onRequest()**, **onConnect()**, **onDisconnect()**, and **onDestory()**. Override them as required. The following figure shows the lifecycle of ServiceExtensionAbility. 30 31**Figure 1** ServiceExtensionAbility lifecycle 32 33 34 35- **onCreate** 36 37 This callback is triggered when a ServiceExtensionAbility is created for the first time. You can perform initialization operations, for example, registering a common event listener. 38 39 > **NOTE** 40 > 41 > If a ServiceExtensionAbility has been created, starting it again does not trigger the **onCreate()** callback. 42 43- **onRequest** 44 45 This callback is triggered when another component calls the [startServiceExtensionAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartserviceextensionability) method to start a ServiceExtensionAbility. After being started, the ServiceExtensionAbility runs in the background. This callback is triggered each time the [startServiceExtensionAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartserviceextensionability) method is called. 46 47- **onConnect** 48 49 This callback is triggered when another component calls the [connectServiceExtensionAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextconnectserviceextensionability) method to connect to a ServiceExtensionAbility. In this method, a remote proxy object (IRemoteObject) is returned, through which the client communicates with the server by means of RPC. At the same time, the system stores the remote proxy object (IRemoteObject). If another component calls the [connectServiceExtensionAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextconnectserviceextensionability) method to connect to this ServiceExtensionAbility, the system directly returns the saved remote proxy object (IRemoteObject) and does not trigger the callback. 50 51- **onDisconnect** 52 53 This callback is triggered when the last connection is disconnected. A connection is disconnected when the client exits or the [disconnectServiceExtensionAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextdisconnectserviceextensionability) method is called. 54 55- **onDestroy** 56 57 This callback is triggered when ServiceExtensionAbility is no longer used and the instance is ready for destruction. You can clear resources in this callback, for example, deregister the listener. 58 59## Implementing a Background Service (for System Applications Only) 60 61### Preparations 62 63Only system applications can implement ServiceExtensionAbility. You must make the following preparations before development: 64 65- **Switching to the full SDK**: All APIs related to ServiceExtensionAbility are marked as system APIs and hidden by default. Therefore, you must manually obtain the full SDK from the mirror and switch to it in DevEco Studio. For details, see [Guide to Switching to Full SDK](../quick-start/full-sdk-switch-guide.md). 66 67- **Requesting the AllowAppUsePrivilegeExtension privilege**: Only applications with the **AllowAppUsePrivilegeExtension** privilege can develop ServiceExtensionAbility. For details about how to request the privilege, see [Application Privilege Configuration Guide](../../device-dev/subsystems/subsys-app-privilege-config-guide.md). 68 69### Defining IDL Interfaces 70 71As a background service, ServiceExtensionAbility needs to provide interfaces that can be called by external systems. You can define the interfaces in IDL files and use the [IDL tool](../IDL/idl-guidelines.md) to generate proxy and stub files. The following demonstrates how to define a file named **IIdlServiceExt.idl**: 72 73```cpp 74interface OHOS.IIdlServiceExt { 75 int ProcessData([in] int data); 76 void InsertDataToMap([in] String key, [in] int val); 77} 78``` 79 80Create the **IdlServiceExt** directory in the **ets** directory corresponding to the module of the DevEco Studio project, and copy the files generated by the [IDL tool](../IDL/idl-guidelines.md) to this directory. Then create a file named **idl_service_ext_impl.ts** to implement the IDL interfaces. 81 82``` 83├── ets 84│ ├── IdlServiceExt 85│ │ ├── i_idl_service_ext.ts # File generated. 86│ │ ├── idl_service_ext_proxy.ts # File generated. 87│ │ ├── idl_service_ext_stub.ts # File generated. 88│ │ ├── idl_service_ext_impl.ts # Custom file used to implement IDL interfaces. 89│ └ 90└ 91``` 92 93An example of **idl_service_ext_impl.ts** is as follows: 94 95```ts 96import {processDataCallback} from './i_idl_service_ext'; 97import {insertDataToMapCallback} from './i_idl_service_ext'; 98import IdlServiceExtStub from './idl_service_ext_stub'; 99 100const ERR_OK = 0; 101const TAG: string = "[IdlServiceExtImpl]"; 102 103// You need to implement interfaces in this type. 104export default class ServiceExtImpl extends IdlServiceExtStub { 105 processData(data: number, callback: processDataCallback): void { 106 // Implement service logic. 107 console.info(TAG, `processData: ${data}`); 108 callback(ERR_OK, data + 1); 109 } 110 111 insertDataToMap(key: string, val: number, callback: insertDataToMapCallback): void { 112 // Implement service logic. 113 console.info(TAG, `insertDataToMap, key: ${key} val: ${val}`); 114 callback(ERR_OK); 115 } 116} 117``` 118 119### Creating a ServiceExtensionAbility 120 121To manually create a ServiceExtensionAbility in the DevEco Studio project, perform the following steps: 122 1231. In the **ets** directory of the **Module** project, right-click and choose **New > Directory** to create a directory named **ServiceExtAbility**. 124 1252. In the **ServiceExtAbility** directory, right-click and choose **New > TypeScript File** to create a file named **ServiceExtAbility.ts**. 126 127 ``` 128 ├── ets 129 │ ├── IdlServiceExt 130 │ │ ├── i_idl_service_ext.ts # File generated. 131 │ │ ├── idl_service_ext_proxy.ts # File generated. 132 │ │ ├── idl_service_ext_stub.ts # File generated. 133 │ │ ├── idl_service_ext_impl.ts # Custom file used to implement IDL interfaces. 134 │ ├── ServiceExtAbility 135 │ │ ├── ServiceExtAbility.ts 136 └ 137 ``` 138 1393. In the **ServiceExtAbility.ts** file, add the dependency package for importing ServiceExtensionAbility. Customize a class that inherits from ServiceExtensionAbility and implement the lifecycle callbacks, and return the previously defined **ServiceExtImpl** object in the **onConnect** lifecycle callback. 140 141 ```ts 142 import ServiceExtensionAbility from '@ohos.app.ability.ServiceExtensionAbility'; 143 import ServiceExtImpl from '../IdlServiceExt/idl_service_ext_impl'; 144 145 const TAG: string = "[ServiceExtAbility]"; 146 147 export default class ServiceExtAbility extends ServiceExtensionAbility { 148 serviceExtImpl = new ServiceExtImpl("ExtImpl"); 149 150 onCreate(want) { 151 console.info(TAG, `onCreate, want: ${want.abilityName}`); 152 } 153 154 onRequest(want, startId) { 155 console.info(TAG, `onRequest, want: ${want.abilityName}`); 156 } 157 158 onConnect(want) { 159 console.info(TAG, `onConnect, want: ${want.abilityName}`); 160 // Return the ServiceExtImpl object, through which the client can communicate with the ServiceExtensionAbility. 161 return this.serviceExtImpl; 162 } 163 164 onDisconnect(want) { 165 console.info(TAG, `onDisconnect, want: ${want.abilityName}`); 166 } 167 168 onDestroy() { 169 console.info(TAG, `onDestroy`); 170 } 171 } 172 ``` 173 1744. Register ServiceExtensionAbility in the [module.json5 file](../quick-start/module-configuration-file.md) corresponding to the **Module** project. Set **type** to **"service"** and **srcEntry** to the code path of the ServiceExtensionAbility component. 175 176 ```json 177 { 178 "module": { 179 ... 180 "extensionAbilities": [ 181 { 182 "name": "ServiceExtAbility", 183 "icon": "$media:icon", 184 "description": "service", 185 "type": "service", 186 "exported": true, 187 "srcEntry": "./ets/ServiceExtAbility/ServiceExtAbility.ts" 188 } 189 ] 190 } 191 } 192 ``` 193 194## Starting a Background Service (for System Applications Only) 195 196A system application uses the [startServiceExtensionAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#abilitycontextstartserviceextensionability) method to start a background service. The [onRequest()](../reference/apis/js-apis-app-ability-serviceExtensionAbility.md#serviceextensionabilityonrequest) callback is invoked, and the **Want** object passed by the caller is received through the callback. After the background service is started, its lifecycle is independent of that of the client. In other words, even if the client is destroyed, the background service can still run. Therefore, the background service must be stopped by calling [terminateSelf()](../reference/apis/js-apis-inner-application-serviceExtensionContext.md#serviceextensioncontextterminateself) when its work is complete. Alternatively, another component can call [stopServiceExtensionAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#abilitycontextstopserviceextensionability) to stop the background service. 197 198> **NOTE** 199> 200> [startServiceExtensionAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#abilitycontextstartserviceextensionability), [stopServiceExtensionAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#abilitycontextstopserviceextensionability), and [terminateSelf()](../reference/apis/js-apis-inner-application-serviceExtensionContext.md#serviceextensioncontextterminateself) of ServiceExtensionContext are system APIs and cannot be called by third-party applications. 201 2021. Start a new ServiceExtensionAbility in a system application. For details about how to obtain the context, see [Obtaining the Context of UIAbility](uiability-usage.md#obtaining-the-context-of-uiability). 203 204 ```ts 205 let context = ...; // UIAbilityContext 206 let want = { 207 "deviceId": "", 208 "bundleName": "com.example.myapplication", 209 "abilityName": "ServiceExtAbility" 210 }; 211 context.startServiceExtensionAbility(want).then(() => { 212 console.info('Succeeded in starting ServiceExtensionAbility.'); 213 }).catch((err) => { 214 console.error(`Failed to start ServiceExtensionAbility. Code is ${err.code}, message is ${err.message}`); 215 }) 216 ``` 217 2182. Stop ServiceExtensionAbility in the system application. 219 220 ```ts 221 let context = ...; // UIAbilityContext 222 let want = { 223 "deviceId": "", 224 "bundleName": "com.example.myapplication", 225 "abilityName": "ServiceExtAbility" 226 }; 227 context.stopServiceExtensionAbility(want).then(() => { 228 console.info('Succeeded in stoping ServiceExtensionAbility.'); 229 }).catch((err) => { 230 console.error(`Failed to stop ServiceExtensionAbility. Code is ${err.code}, message is ${err.message}`); 231 }) 232 ``` 233 2343. ServiceExtensionAbility stops itself. 235 236 ```ts 237 let context = ...; // ServiceExtensionContext 238 context.terminateSelf().then(() => { 239 console.info('Succeeded in terminating self.'); 240 }).catch((err) => { 241 console.error(`Failed to terminate self. Code is ${err.code}, message is ${err.message}`); 242 }) 243 ``` 244 245> **NOTE** 246> 247> Background services can run in the background for a long time. To minimize resource usage, destroy it in time when a background service finishes the task of the requester. A background service can be stopped in either of the following ways: 248> 249> - The background service calls the [terminateSelf()](../reference/apis/js-apis-inner-application-serviceExtensionContext.md#serviceextensioncontextterminateself) method to automatically stop itself. 250> - Another component calls the [stopServiceExtensionAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#abilitycontextstopserviceextensionability) method to stop the background service. 251> After either method is called, the system destroys the background service. 252 253## Connecting to a Background Service 254 255Either a system application or a third-party application can connect to a ServiceExtensionAbility (specified in the **Want** object) through [connectServiceExtensionAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#abilitycontextconnectserviceextensionability). The [onConnect()](../reference/apis/js-apis-app-ability-serviceExtensionAbility.md#serviceextensionabilityonconnect) callback is invoked, and the **Want** object passed by the caller is received through the callback. In this way, a persistent connection is established. 256 257The ServiceExtensionAbility component returns an IRemoteObject in the **onConnect()** callback. Through this IRemoteObject, you can define communication interfaces for RPC interaction between the client and server. Multiple clients can connect to the same background service at the same time. After a client finishes the interaction, it must call [disconnectServiceExtensionAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#abilitycontextdisconnectserviceextensionability) to disconnect from the service. If all clients connected to a background service are disconnected, the system destroys the service. 258 259- Call **connectServiceExtensionAbility()** to establish a connection to a background service. For details about how to obtain the context, see [Obtaining the Context of UIAbility](uiability-usage.md#obtaining-the-context-of-uiability). 260 261 ```ts 262 let want = { 263 "deviceId": "", 264 "bundleName": "com.example.myapplication", 265 "abilityName": "ServiceExtAbility" 266 }; 267 let options = { 268 onConnect(elementName, remote) { 269 /* The input parameter remote is the object returned by ServiceExtensionAbility in the onConnect lifecycle callback. 270 * This object is used for communication with ServiceExtensionAbility. For details, see the section below. 271 */ 272 console.info('onConnect callback'); 273 if (remote === null) { 274 console.info(`onConnect remote is null`); 275 return; 276 } 277 }, 278 onDisconnect(elementName) { 279 console.info('onDisconnect callback') 280 }, 281 onFailed(code) { 282 console.info('onFailed callback') 283 } 284 } 285 // The ID returned after the connection is set up must be saved. The ID will be passed for service disconnection. 286 let connectionId = this.context.connectServiceExtensionAbility(want, options); 287 ``` 288 289- Use **disconnectServiceExtensionAbility()** to disconnect from the background service. 290 291 ```ts 292 // connectionId is returned when connectServiceExtensionAbility is called and needs to be manually maintained. 293 this.context.disconnectServiceExtensionAbility(connectionId).then((data) => { 294 console.info('disconnectServiceExtensionAbility success'); 295 }).catch((error) => { 296 console.error('disconnectServiceExtensionAbility failed'); 297 }) 298 ``` 299 300## Communication Between the Client and Server 301 302After obtaining the [rpc.RemoteObject](../reference/apis/js-apis-rpc.md#iremoteobject) object from the **onConnect()** callback, the client can communicate with ServiceExtensionAbility in either of the following ways: 303 304- Using the IDL interface provided by the server for communication (recommended) 305 306 ```ts 307 // The client needs to import idl_service_ext_proxy.ts provided by the server for external systems to the local project. 308 import IdlServiceExtProxy from '../IdlServiceExt/idl_service_ext_proxy'; 309 310 let options = { 311 onConnect(elementName, remote) { 312 console.info('onConnect callback'); 313 if (remote === null) { 314 console.info(`onConnect remote is null`); 315 return; 316 } 317 let serviceExtProxy = new IdlServiceExtProxy(remote); 318 // Communication is carried out by interface calling, without exposing RPC details. 319 serviceExtProxy.processData(1, (errorCode, retVal) => { 320 console.info(`processData, errorCode: ${errorCode}, retVal: ${retVal}`); 321 }); 322 serviceExtProxy.insertDataToMap('theKey', 1, (errorCode) => { 323 console.info(`insertDataToMap, errorCode: ${errorCode}`); 324 }) 325 }, 326 onDisconnect(elementName) { 327 console.info('onDisconnect callback') 328 }, 329 onFailed(code) { 330 console.info('onFailed callback') 331 } 332 } 333 ``` 334 335- Calling [sendMessageRequest](../reference/apis/js-apis-rpc.md#sendmessagerequest9) to send messages to the server (not recommended) 336 337 ```ts 338 import rpc from '@ohos.rpc'; 339 340 const REQUEST_CODE = 1; 341 let options = { 342 onConnect(elementName, remote) { 343 console.info('onConnect callback'); 344 if (remote === null) { 345 console.info(`onConnect remote is null`); 346 return; 347 } 348 // Directly call the RPC interface to send messages to the server. The client needs to serialize the input parameters and deserialize the return values. The process is complex. 349 let option = new rpc.MessageOption(); 350 let data = new rpc.MessageSequence(); 351 let reply = new rpc.MessageSequence(); 352 data.writeInt(100); 353 354 // @param code Indicates the service request code sent by the client. 355 // @param data Indicates the {@link MessageSequence} object sent by the client. 356 // @param reply Indicates the response message object sent by the remote service. 357 // @param options Specifies whether the operation is synchronous or asynchronous. 358 // 359 // @return Returns {@code true} if the operation is successful; returns {@code false} otherwise. 360 remote.sendMessageRequest(REQUEST_CODE, data, reply, option).then((ret) => { 361 let msg = reply.readInt(); 362 console.info(`sendMessageRequest ret:${ret} msg:${msg}`); 363 }).catch((error) => { 364 console.info('sendMessageRequest failed'); 365 }); 366 }, 367 onDisconnect(elementName) { 368 console.info('onDisconnect callback') 369 }, 370 onFailed(code) { 371 console.info('onFailed callback') 372 } 373 } 374 ``` 375 376## Client Identity Verification by the Server 377 378When ServiceExtensionAbility is used to provide sensitive services, the client identity must be verified. You can implement the verification on the stub of the IDL interface. For details about the IDL interface implementation, see [Defining IDL Interfaces](#defining-idl-interfaces). Two verification modes are recommended: 379 380- **Verifying the client identity based on callerUid** 381 382 Call the [getCallingUid()](../reference/apis/js-apis-rpc.md#getcallinguid) method to obtain the UID of the client, and then call the [getBundleNameByUid()](../reference/apis/js-apis-bundleManager.md#bundlemanagergetbundlenamebyuid) method to obtain the corresponding bundle name. In this way, the client identify is verified. Note that [getBundleNameByUid()](../reference/apis/js-apis-bundleManager.md#bundlemanagergetbundlenamebyuid) is asynchronous, and therefore the server cannot return the verification result to the client. This verification mode applies when the client sends an asynchronous task execution request to the server. The sample code is as follows: 383 384 ```ts 385 import rpc from '@ohos.rpc'; 386 import bundleManager from '@ohos.bundle.bundleManager'; 387 import { processDataCallback } from './i_idl_service_ext'; 388 import { insertDataToMapCallback } from './i_idl_service_ext'; 389 import IdlServiceExtStub from './idl_service_ext_stub'; 390 391 const ERR_OK = 0; 392 const ERR_DENY = -1; 393 const TAG: string = "[IdlServiceExtImpl]"; 394 395 export default class ServiceExtImpl extends IdlServiceExtStub { 396 processData(data: number, callback: processDataCallback): void { 397 console.info(TAG, `processData: ${data}`); 398 399 let callerUid = rpc.IPCSkeleton.getCallingUid(); 400 bundleManager.getBundleNameByUid(callerUid).then((callerBundleName) => { 401 console.info(TAG, 'getBundleNameByUid: ' + callerBundleName); 402 // Identify the bundle name of the client. 403 if (callerBundleName != 'com.example.connectextapp') { // The verification fails. 404 console.info(TAG, 'The caller bundle is not in trustlist, reject'); 405 return; 406 } 407 // The verification is successful, and service logic is executed normally. 408 }).catch(err => { 409 console.info(TAG, 'getBundleNameByUid failed: ' + err.message); 410 }); 411 } 412 413 insertDataToMap(key: string, val: number, callback: insertDataToMapCallback): void { 414 // Implement service logic. 415 console.info(TAG, `insertDataToMap, key: ${key} val: ${val}`); 416 callback(ERR_OK); 417 } 418 } 419 ``` 420 421- **Verifying the client identity based on callerTokenId** 422 423 Call the [getCallingTokenId()](../reference/apis/js-apis-rpc.md#getcallingtokenid) method to obtain the token ID of the client, and then call the [verifyAccessTokenSync()](../reference/apis/js-apis-abilityAccessCtrl.md#verifyaccesstokensync) method to check whether the client has a specific permission. Currently, OpenHarmony does not support permission customization. Therefore, only [system-defined permissions](../security/permission-list.md) can be verified. The sample code is as follows: 424 425 ```ts 426 import rpc from '@ohos.rpc'; 427 import abilityAccessCtrl from '@ohos.abilityAccessCtrl'; 428 import {processDataCallback} from './i_idl_service_ext'; 429 import {insertDataToMapCallback} from './i_idl_service_ext'; 430 import IdlServiceExtStub from './idl_service_ext_stub'; 431 432 const ERR_OK = 0; 433 const ERR_DENY = -1; 434 const TAG: string = "[IdlServiceExtImpl]"; 435 436 export default class ServiceExtImpl extends IdlServiceExtStub { 437 processData(data: number, callback: processDataCallback): void { 438 console.info(TAG, `processData: ${data}`); 439 440 let callerTokenId = rpc.IPCSkeleton.getCallingTokenId(); 441 let accessManger = abilityAccessCtrl.createAtManager(); 442 // The permission to be verified varies depending on the service requirements. ohos.permission.SET_WALLPAPER is only an example. 443 let grantStatus = 444 accessManger.verifyAccessTokenSync(callerTokenId, "ohos.permission.SET_WALLPAPER"); 445 if (grantStatus === abilityAccessCtrl.GrantStatus.PERMISSION_DENIED) { 446 console.info(TAG, `PERMISSION_DENIED`); 447 callback(ERR_DENY, data); // The verification fails and an error is returned. 448 return; 449 } 450 callback(ERR_OK, data + 1); // The verification is successful, and service logic is executed normally. 451 } 452 453 insertDataToMap(key: string, val: number, callback: insertDataToMapCallback): void { 454 // Implement service logic. 455 console.info(TAG, `insertDataToMap, key: ${key} val: ${val}`); 456 callback(ERR_OK); 457 } 458 } 459 ``` 460 461