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