• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# ServiceExtensionAbility开发指导
2
3## 场景介绍
4ExtensionAbility,是Stage模型中新增的扩展组件的基类,一般用于处理无界面的任务,生命周期较简单,没有前后台生命周期。ServiceExtensionAbility是ExtensionAbility的扩展类。
5
6开发者可以自定义类继承ServiceExtensionAbility,通过重写基类中相关生命周期方法,来做初始化、连接中、断开连接时相关业务逻辑操作。
7
8## 接口说明
9
10**表1** ServiceExtensionAbility中相关生命周期API功能介绍
11|接口名|描述|
12|:------|:------|
13|onCreate(want: Want): void|首次调用startAbility、connectAbility时触发,开发者可以进行初始化操作。|
14|onRequest(want: Want, startId: number): void|每次调用startAbility都会触发,首次调用时startId为1,重复调用startAbility递增。|
15|onConnect(want: Want): rpc.RemoteObject|调用connectAbility触发,重复调用不会再次触发,除非调用disconnectAbility解除绑定后再调用;onConnect返回一个进程通信类RemoteObject。|
16|onDisconnect(want: Want): void|调用disconnectAbility触发,Extension如果是用connectAbility拉起的,并且已经没有其他应用绑定这个Extension,则会触发onDestroy生命周期销毁组件。|
17|onDestroy(): void|调用停止当前ability接口terminateSelf会触发。|
18
19
20## 约束与限制
21
22OpenHarmony当前不支持三方应用创建ServiceExtensionAbility。
23
24
25## 开发步骤
26
271. 需要在应用配置文件module.json5中进行注册,注册类型type需要设置为service。module.json5配置样例如下所示:
28
29
30   ```json
31    "extensionAbilities":[{
32        "name": "ServiceExtAbility",
33        "icon": "$media:icon",
34        "description": "service",
35        "type": "service",
36        "exported": true,
37        "srcEnty": "./ets/ServiceExtAbility/ServiceExtAbility.ts"
38    }]
39   ```
40
41
422. 开发者在定义Service的目录下创建TS文件,自定义类继承ServiceExtensionAbility,重写基类回调函数,接口生成的默认相对路径:entry\src\main\ets\ServiceExtAbility\ServiceExtAbility.ts,示例如下:
43
44    ```js
45    import ServiceExtensionAbility from '@ohos.application.ServiceExtensionAbility'
46    import rpc from '@ohos.rpc'
47
48    class StubTest extends rpc.RemoteObject {
49        constructor(des) {
50            super(des);
51        }
52        onRemoteRequest(code, data, reply, option) {
53        }
54    }
55
56    class ServiceExtAbility extends ServiceExtensionAbility {
57        onCreate(want) {
58            console.log('onCreate, want:' + want.abilityName);
59        }
60        onRequest(want, startId) {
61            console.log('onRequest, want:' + want.abilityName);
62        }
63        onConnect(want) {
64            console.log('onConnect , want:' + want.abilityName);
65            return new StubTest("test");
66        }
67        onDisconnect(want) {
68            console.log('onDisconnect, want:' + want.abilityName);
69        }
70        onDestroy() {
71            console.log('onDestroy');
72        }
73    }
74    ```