1# ServiceExtensionAbility 2 3 4[ServiceExtensionAbility](../reference/apis/js-apis-app-ability-serviceExtensionAbility.md) is an ExtensionAbility component of the service type that provides extension capabilities related to background services. 5 6 7ServiceExtensionAbility can be started or connected by other application 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#abilitycontextstartserviceextensionability) method to start background services or call the [connectServiceExtensionAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#abilitycontextconnectserviceextensionability) 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: 8 9 10- In the case that AbilityA starts ServiceB, they are weakly associated. After AbilityA exits, ServiceB can still exist. 11 12- In the case that AbilityA connects to ServiceB, they are strongly associated. After AbilityA exits, ServiceB also exits. 13 14 15Each type of ExtensionAbility has its own context. ServiceExtensionAbility has [ServiceExtensionContext](../reference/apis/js-apis-inner-application-serviceExtensionContext.md). In this document, the started ServiceExtensionAbility component is called the server, and the component that starts ServiceExtensionAbility is called the client. 16 17 18This topic describes how to use ServiceExtensionAbility in the following scenarios: 19 20 21- [Implementing a Background Service (for System Applications Only)](#implementing-a-background-service-for-system-applications-only) 22 23- [Starting a Background Service (for System Applications Only)](#starting-a-background-service-for-system-applications-only) 24 25- [Connecting to a Background Service](#connecting-to-a-background-service) 26 27 28> **NOTE** 29> - OpenHarmony does not support third-party applications in implementing 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). 30> 31> - UIAbility of a third-party application can connect to ServiceExtensionAbility provided by the system through the context. 32> 33> - Third-party applications can connect to ServiceExtensionAbility provided by the system only when they gain focus in the foreground. 34 35 36## Implementing a Background Service (for System Applications Only) 37 38[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. 39 40 **Figure 1** ServiceExtensionAbility lifecycle 41 42 43- **onCreate** 44 45 This callback is triggered when a service is created for the first time. You can perform initialization operations, for example, registering a common event listener. 46 47 > **NOTE** 48 > 49 > If a service has been created, starting it again does not trigger the **onCreate()** callback. 50 51- **onRequest** 52 53 This callback is triggered when another component calls the **startServiceExtensionAbility()** method to start the service. After being started, the service runs in the background. 54 55- **onConnect** 56 57 This callback is triggered when another component calls the **connectServiceExtensionAbility()** method to connect to the service. In this method, a remote proxy object (IRemoteObject) is returned, through which the client communicates with the server by means of RPC. 58 59- **onDisconnect** 60 61 This callback is triggered when a component calls the **disconnectServiceExtensionAbility()** method to disconnect from the service. 62 63- **onDestroy** 64 65 This callback is triggered when the service is no longer used and the instance is ready for destruction. You can clear resources in this callback, for example, deregister the listener. 66 67 68## How to Develop 69 70To implement a background service, manually create a ServiceExtensionAbility component in DevEco Studio. The procedure is as follows: 71 721. In the **ets** directory of the **Module** project, right-click and choose **New > Directory** to create a directory named **serviceextability**. 73 742. In the **serviceextability** directory, right-click and choose **New > TypeScript File** to create a file named **ServiceExtAbility.ts**. 75 763. Open the **ServiceExtAbility.ts** file, import the [RPC module](../reference/apis/js-apis-rpc.md), and reload the **onRemoteMessageRequest()** method to receive messages from the client and return the processing result to the client. **REQUEST_VALUE** is used to verify the service request code sent by the client. 77 78 ```ts 79 import rpc from '@ohos.rpc'; 80 81 const REQUEST_CODE = 99; 82 83 class StubTest extends rpc.RemoteObject { 84 constructor(des) { 85 super(des); 86 } 87 88 // Receive a message from the client and return the processing result to the client. 89 onRemoteMessageRequest(code, data, reply, option) { 90 if (code === REQUEST_CODE) { 91 // Receive data from the client. 92 // If the client calls data.writeInt() multiple times to write multiple pieces of data, the server can call data.readInt() multiple times to receive all the data. 93 let optFir = data.readInt(); 94 let optSec = data.readInt(); 95 // The server returns the data processing result to the client. 96 // In the example, the server receives two pieces of data and returns the sum of the two pieces of data to the client. 97 reply.writeInt(optFir + optSec); 98 } 99 return true; 100 } 101 102 // Send messages to the client in synchronous or asynchronous mode. 103 sendRequest(code, data, reply, options) { 104 return null; 105 } 106 } 107 ``` 108 1094. In the **ServiceExtAbility.ts** file, add the dependency package for importing ServiceExtensionAbility. Customize a class that inherits from ServiceExtensionAbility and add the required lifecycle callbacks. 110 111 ```ts 112 import ServiceExtensionAbility from '@ohos.app.ability.ServiceExtensionAbility'; 113 import rpc from '@ohos.rpc'; 114 115 const TAG: string = "[Example].[Entry].[ServiceExtAbility]"; 116 const REQUEST_CODE = 99; 117 118 class StubTest extends rpc.RemoteObject { 119 // ... 120 } 121 122 export default class ServiceExtAbility extends ServiceExtensionAbility { 123 onCreate(want) { 124 console.info(TAG, `onCreate, want: ${want.abilityName}`); 125 } 126 127 onRequest(want, startId) { 128 console.info(TAG, `onRequest, want: ${want.abilityName}`); 129 } 130 131 onConnect(want) { 132 console.info(TAG, `onConnect, want: ${want.abilityName}`); 133 return new StubTest("test"); 134 } 135 136 onDisconnect(want) { 137 console.info(TAG, `onDisconnect, want: ${want.abilityName}`); 138 } 139 140 onDestroy() { 141 console.info(TAG, `onDestroy`); 142 } 143 } 144 ``` 145 1465. Register ServiceExtensionAbility in the [module.json5 file](../quick-start/module-configuration-file.md) corresponding to the **Module** project. Set **type** to **"service"** and **srcEntrance** to the code path of the ExtensionAbility component. 147 148 ```json 149 { 150 "module": { 151 // ... 152 "extensionAbilities": [ 153 { 154 "name": "ServiceExtAbility", 155 "icon": "$media:icon", 156 "description": "service", 157 "type": "service", 158 "visible": true, 159 "srcEntrance": "./ets/serviceextability/ServiceExtAbility.ts" 160 } 161 ] 162 } 163 } 164 ``` 165 166 167## Starting a Background Service (for System Applications Only) 168 169A 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. 170 171> **NOTE** 172> 173> [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. 174 1751. 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). 176 177 ```ts 178 let want = { 179 "deviceId": "", 180 "bundleName": "com.example.myapplication", 181 "abilityName": "ServiceExtAbility" 182 }; 183 this.context.startServiceExtensionAbility(want).then(() => { 184 console.info('startServiceExtensionAbility success'); 185 }).catch((error) => { 186 console.info('startServiceExtensionAbility failed'); 187 }) 188 ``` 189 1902. Stop ServiceExtensionAbility in the system application. 191 192 ```ts 193 let want = { 194 "deviceId": "", 195 "bundleName": "com.example.myapplication", 196 "abilityName": "ServiceExtAbility" 197 }; 198 this.context.stopServiceExtensionAbility(want).then(() => { 199 console.info('stopServiceExtensionAbility success'); 200 }).catch((error) => { 201 console.info('stopServiceExtensionAbility failed'); 202 }) 203 ``` 204 2053. ServiceExtensionAbility stops itself. 206 207 ```ts 208 // this is the current ServiceExtensionAbility component. 209 this.context.terminateSelf().then(() => { 210 console.info('terminateSelf success'); 211 }).catch((error) => { 212 console.info('terminateSelf failed'); 213 }) 214 ``` 215 216 217> **NOTE** 218> 219> 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: 220> 221> - The background service calls the [terminateSelf()](../reference/apis/js-apis-inner-application-serviceExtensionContext.md#serviceextensioncontextterminateself) method to automatically stop itself. 222> 223> - Another component calls the [stopServiceExtensionAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#abilitycontextstopserviceextensionability) method to stop the background service. 224> 225> After either method is called, the system destroys the background service. 226 227 228## Connecting to a Background Service 229 230Either a system application or a third-party application can connect to a service (service 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. 231 232The 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. 233 234- 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). 235 236 ```ts 237 import rpc from '@ohos.rpc'; 238 239 const REQUEST_CODE = 99; 240 let want = { 241 "deviceId": "", 242 "bundleName": "com.example.myapplication", 243 "abilityName": "ServiceExtAbility" 244 }; 245 let options = { 246 onConnect(elementName, remote) { 247 console.info('onConnect callback'); 248 if (remote === null) { 249 console.info(`onConnect remote is null`); 250 return; 251 } 252 let option = new rpc.MessageOption(); 253 let data = new rpc.MessageParcel(); 254 let reply = new rpc.MessageParcel(); 255 data.writeInt(100); 256 data.writeInt(200); 257 258 // @param code Indicates the service request code sent by the client. 259 // @param data Indicates the {@link MessageParcel} object sent by the client. 260 // @param reply Indicates the response message object sent by the remote service. 261 // @param options Specifies whether the operation is synchronous or asynchronous. 262 // 263 // @return Returns {@code true} if the operation is successful; returns {@code false} otherwise. 264 remote.sendRequest(REQUEST_CODE, data, reply, option).then((ret) => { 265 let msg = reply.readInt(); 266 console.info(`sendRequest ret:${ret} msg:${msg}`); 267 }).catch((error) => { 268 console.info('sendRequest failed'); 269 }); 270 }, 271 onDisconnect(elementName) { 272 console.info('onDisconnect callback') 273 }, 274 onFailed(code) { 275 console.info('onFailed callback') 276 } 277 } 278 // The ID returned after the connection is set up must be saved. The ID will be passed for service disconnection. 279 let connectionId = this.context.connectServiceExtensionAbility(want, options); 280 ``` 281 282- Use **disconnectServiceExtensionAbility()** to disconnect from the background service. 283 284 ```ts 285 let connectionId = 1 // ID returned when the service is connected through connectServiceExtensionAbility. 286 this.context.disconnectServiceExtensionAbility(connectionId).then((data) => { 287 console.info('disconnectServiceExtensionAbility success'); 288 }).catch((error) => { 289 console.error('disconnectServiceExtensionAbility failed'); 290 }) 291 ``` 292 293