• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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![ServiceExtensionAbility-lifecycle](figures/ServiceExtensionAbility-lifecycle.png)
33
34- **onCreate**
35
36  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.
37
38  > **NOTE**
39  >
40  > If a ServiceExtensionAbility has been created, starting it again does not trigger the **onCreate()** callback.
41
42- **onRequest**
43
44  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.
45
46- **onConnect**
47
48  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.
49
50- **onDisconnect**
51
52  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.
53
54- **onDestroy**
55
56  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.
57
58## Implementing a Background Service (for System Applications Only)
59
60### Preparations
61
62Only system applications can implement ServiceExtensionAbility. You must make the following preparations before development:
63
64- **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).
65
66- **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).
67
68### Defining IDL Interfaces
69
70As 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**:
71
72```cpp
73interface OHOS.IIdlServiceExt {
74  int ProcessData([in] int data);
75  void InsertDataToMap([in] String key, [in] int val);
76}
77```
78
79Create 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.
80
81```
82├── ets
83│ ├── IdlServiceExt
84│ │   ├── i_idl_service_ext.ts      # File generated.
85│ │   ├── idl_service_ext_proxy.ts  # File generated.
86│ │   ├── idl_service_ext_stub.ts   # File generated.
87│ │   ├── idl_service_ext_impl.ts   # Custom file used to implement IDL interfaces.
88│ └
8990```
91
92An example of **idl_service_ext_impl.ts** is as follows:
93
94```ts
95import {processDataCallback} from './i_idl_service_ext';
96import {insertDataToMapCallback} from './i_idl_service_ext';
97import IdlServiceExtStub from './idl_service_ext_stub';
98
99const ERR_OK = 0;
100const TAG: string = "[IdlServiceExtImpl]";
101
102// You need to implement interfaces in this type.
103export default class ServiceExtImpl extends IdlServiceExtStub {
104  processData(data: number, callback: processDataCallback): void {
105    // Implement service logic.
106    console.info(TAG, `processData: ${data}`);
107    callback(ERR_OK, data + 1);
108  }
109
110  insertDataToMap(key: string, val: number, callback: insertDataToMapCallback): void {
111    // Implement service logic.
112    console.log(TAG, `insertDataToMap, key: ${key}  val: ${val}`);
113    callback(ERR_OK);
114  }
115}
116```
117
118### Creating a ServiceExtensionAbility
119
120To manually create a ServiceExtensionAbility in the DevEco Studio project, perform the following steps:
121
1221. In the **ets** directory of the **Module** project, right-click and choose **New > Directory** to create a directory named **ServiceExtAbility**.
123
1242. In the **ServiceExtAbility** directory, right-click and choose **New > TypeScript File** to create a file named **ServiceExtAbility.ts**.
125
126    ```
127    ├── ets
128    │ ├── IdlServiceExt
129    │ │   ├── i_idl_service_ext.ts      # File generated.
130    │ │   ├── idl_service_ext_proxy.ts  # File generated.
131    │ │   ├── idl_service_ext_stub.ts   # File generated.
132    │ │   ├── idl_service_ext_impl.ts   # Custom file used to implement IDL interfaces.
133    │ ├── ServiceExtAbility
134    │ │   ├── ServiceExtAbility.ts
135136    ```
137
1383. 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.
139
140   ```ts
141   import ServiceExtensionAbility from '@ohos.app.ability.ServiceExtensionAbility';
142   import ServiceExtImpl from '../IdlServiceExt/idl_service_ext_impl';
143
144   const TAG: string = "[ServiceExtAbility]";
145
146   export default class ServiceExtAbility extends ServiceExtensionAbility {
147     serviceExtImpl = new ServiceExtImpl("ExtImpl");
148
149     onCreate(want) {
150       console.info(TAG, `onCreate, want: ${want.abilityName}`);
151     }
152
153     onRequest(want, startId) {
154       console.info(TAG, `onRequest, want: ${want.abilityName}`);
155     }
156
157     onConnect(want) {
158       console.info(TAG, `onConnect, want: ${want.abilityName}`);
159       // Return the ServiceExtImpl object, through which the client can communicate with the ServiceExtensionAbility.
160       return this.serviceExtImpl;
161     }
162
163     onDisconnect(want) {
164       console.info(TAG, `onDisconnect, want: ${want.abilityName}`);
165     }
166
167     onDestroy() {
168       console.info(TAG, `onDestroy`);
169     }
170   }
171   ```
172
1734. 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.
174
175   ```json
176   {
177     "module": {
178       // ...
179       "extensionAbilities": [
180         {
181           "name": "ServiceExtAbility",
182           "icon": "$media:icon",
183           "description": "service",
184           "type": "service",
185           "exported": true,
186           "srcEntry": "./ets/ServiceExtAbility/ServiceExtAbility.ts"
187         }
188       ]
189     }
190   }
191   ```
192
193## Starting a Background Service (for System Applications Only)
194
195A 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.
196
197> **NOTE**
198>
199> [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.
200
2011. 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).
202
203   ```ts
204   let want = {
205       "deviceId": "",
206       "bundleName": "com.example.myapplication",
207       "abilityName": "ServiceExtAbility"
208   };
209   this.context.startServiceExtensionAbility(want).then(() => {
210       console.info('startServiceExtensionAbility success');
211   }).catch((error) => {
212       console.info('startServiceExtensionAbility failed');
213   })
214   ```
215
2162. Stop ServiceExtensionAbility in the system application.
217
218   ```ts
219   let want = {
220       "deviceId": "",
221       "bundleName": "com.example.myapplication",
222       "abilityName": "ServiceExtAbility"
223   };
224   this.context.stopServiceExtensionAbility(want).then(() => {
225       console.info('stopServiceExtensionAbility success');
226   }).catch((error) => {
227       console.info('stopServiceExtensionAbility failed');
228   })
229   ```
230
2313. ServiceExtensionAbility stops itself.
232
233   ```ts
234   // this is the current ServiceExtensionAbility component.
235   this.context.terminateSelf().then(() => {
236       console.info('terminateSelf success');
237   }).catch((error) => {
238       console.info('terminateSelf failed');
239   })
240   ```
241
242> **NOTE**
243>
244> 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:
245>
246> - The background service calls the [terminateSelf()](../reference/apis/js-apis-inner-application-serviceExtensionContext.md#serviceextensioncontextterminateself) method to automatically stop itself.
247> - Another component calls the [stopServiceExtensionAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#abilitycontextstopserviceextensionability) method to stop the background service.
248> After either method is called, the system destroys the background service.
249
250## Connecting to a Background Service
251
252Either 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.
253
254The 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.
255
256- 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).
257
258  ```ts
259  let want = {
260      "deviceId": "",
261      "bundleName": "com.example.myapplication",
262      "abilityName": "ServiceExtAbility"
263  };
264  let options = {
265      onConnect(elementName, remote) {
266          /* The input parameter remote is the object returned by ServiceExtensionAbility in the onConnect lifecycle callback.
267           * This object is used for communication with ServiceExtensionAbility. For details, see the section below.
268           */
269          console.info('onConnect callback');
270          if (remote === null) {
271              console.info(`onConnect remote is null`);
272              return;
273          }
274      },
275      onDisconnect(elementName) {
276          console.info('onDisconnect callback')
277      },
278      onFailed(code) {
279          console.info('onFailed callback')
280      }
281  }
282  // The ID returned after the connection is set up must be saved. The ID will be passed for service disconnection.
283  let connectionId = this.context.connectServiceExtensionAbility(want, options);
284  ```
285
286- Use **disconnectServiceExtensionAbility()** to disconnect from the background service.
287
288  ```ts
289  // connectionId is returned when connectServiceExtensionAbility is called and needs to be manually maintained.
290  this.context.disconnectServiceExtensionAbility(connectionId).then((data) => {
291      console.info('disconnectServiceExtensionAbility success');
292  }).catch((error) => {
293      console.error('disconnectServiceExtensionAbility failed');
294  })
295  ```
296
297## Communication Between the Client and Server
298
299After 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:
300
301- Using the IDL interface provided by the server for communication (recommended)
302
303  ```ts
304  // The client needs to import idl_service_ext_proxy.ts provided by the server for external systems to the local project.
305  import IdlServiceExtProxy from '../IdlServiceExt/idl_service_ext_proxy';
306
307  let options = {
308      onConnect(elementName, remote) {
309          console.info('onConnect callback');
310          if (remote === null) {
311              console.info(`onConnect remote is null`);
312              return;
313          }
314          let serviceExtProxy = new IdlServiceExtProxy(remote);
315          // Communication is carried out by interface calling, without exposing RPC details.
316          serviceExtProxy.processData(1, (errorCode, retVal) => {
317              console.log(`processData, errorCode: ${errorCode}, retVal: ${retVal}`);
318          });
319          serviceExtProxy.insertDataToMap('theKey', 1, (errorCode) => {
320              console.log(`insertDataToMap, errorCode: ${errorCode}`);
321          })
322      },
323      onDisconnect(elementName) {
324          console.info('onDisconnect callback')
325      },
326      onFailed(code) {
327          console.info('onFailed callback')
328      }
329  }
330  ```
331
332- Calling [sendMessageRequest](../reference/apis/js-apis-rpc.md#sendmessagerequest9) to send messages to the server (not recommended)
333
334  ```ts
335  import rpc from '@ohos.rpc';
336
337  const REQUEST_CODE = 1;
338  let options = {
339      onConnect(elementName, remote) {
340          console.info('onConnect callback');
341          if (remote === null) {
342              console.info(`onConnect remote is null`);
343              return;
344          }
345          // 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.
346          let option = new rpc.MessageOption();
347          let data = new rpc.MessageSequence();
348          let reply = new rpc.MessageSequence();
349          data.writeInt(100);
350
351          // @param code Indicates the service request code sent by the client.
352          // @param data Indicates the {@link MessageSequence} object sent by the client.
353          // @param reply Indicates the response message object sent by the remote service.
354          // @param options Specifies whether the operation is synchronous or asynchronous.
355          //
356          // @return Returns {@code true} if the operation is successful; returns {@code false} otherwise.
357          remote.sendMessageRequest(REQUEST_CODE, data, reply, option).then((ret) => {
358              let msg = reply.readInt();
359              console.info(`sendMessageRequest ret:${ret} msg:${msg}`);
360          }).catch((error) => {
361              console.info('sendMessageRequest failed');
362          });
363      },
364      onDisconnect(elementName) {
365          console.info('onDisconnect callback')
366      },
367      onFailed(code) {
368          console.info('onFailed callback')
369      }
370  }
371  ```
372
373## Client Identity Verification by the Server
374
375When 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:
376
377- **Verifying the client identity based on callerUid**
378
379  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:
380
381  ```ts
382  import rpc from '@ohos.rpc';
383  import bundleManager from '@ohos.bundle.bundleManager';
384  import {processDataCallback} from './i_idl_service_ext';
385  import {insertDataToMapCallback} from './i_idl_service_ext';
386  import IdlServiceExtStub from './idl_service_ext_stub';
387
388  const ERR_OK = 0;
389  const ERR_DENY = -1;
390  const TAG: string = "[IdlServiceExtImpl]";
391
392  export default class ServiceExtImpl extends IdlServiceExtStub {
393    processData(data: number, callback: processDataCallback): void {
394      console.info(TAG, `processData: ${data}`);
395
396      let callerUid = rpc.IPCSkeleton.getCallingUid();
397      bundleManager.getBundleNameByUid(callerUid).then((callerBundleName) => {
398        console.info(TAG, 'getBundleNameByUid: ' + callerBundleName);
399        // Identify the bundle name of the client.
400        if (callerBundleName != 'com.example.connectextapp') {  // The verification fails.
401          console.info(TAG, 'The caller bundle is not in whitelist, reject');
402          return;
403        }
404        // The verification is successful, and service logic is executed normally.
405      }).catch(err => {
406        console.info(TAG, 'getBundleNameByUid failed: ' + err.message);
407      });
408    }
409
410    insertDataToMap(key: string, val: number, callback: insertDataToMapCallback): void {
411      // Implement service logic.
412      console.log(TAG, `insertDataToMap, key: ${key}  val: ${val}`);
413      callback(ERR_OK);
414    }
415  }
416  ```
417
418- **Verifying the client identity based on callerTokenId**
419
420  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:
421
422  ```ts
423  import rpc from '@ohos.rpc';
424  import abilityAccessCtrl from '@ohos.abilityAccessCtrl';
425  import {processDataCallback} from './i_idl_service_ext';
426  import {insertDataToMapCallback} from './i_idl_service_ext';
427  import IdlServiceExtStub from './idl_service_ext_stub';
428
429  const ERR_OK = 0;
430  const ERR_DENY = -1;
431  const TAG: string = "[IdlServiceExtImpl]";
432
433  export default class ServiceExtImpl extends IdlServiceExtStub {
434    processData(data: number, callback: processDataCallback): void {
435      console.info(TAG, `processData: ${data}`);
436
437      let callerTokenId = rpc.IPCSkeleton.getCallingTokenId();
438      let accessManger = abilityAccessCtrl.createAtManager();
439      // The permission to be verified varies depending on the service requirements. ohos.permission.SET_WALLPAPER is only an example.
440      let grantStatus =
441          accessManger.verifyAccessTokenSync(callerTokenId, "ohos.permission.SET_WALLPAPER");
442      if (grantStatus === abilityAccessCtrl.GrantStatus.PERMISSION_DENIED) {
443          console.info(TAG, `PERMISSION_DENIED`);
444          callback(ERR_DENY, data);   // The verification fails and an error is returned.
445          return;
446      }
447      callback(ERR_OK, data + 1);     // The verification is successful, and service logic is executed normally.
448    }
449
450    insertDataToMap(key: string, val: number, callback: insertDataToMapCallback): void {
451      // Implement service logic.
452      console.log(TAG, `insertDataToMap, key: ${key}  val: ${val}`);
453      callback(ERR_OK);
454    }
455  }
456  ```
457
458