• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# 创建ServiceAbility
2
3
41. 创建ServiceAbility。
5
6     重写ServiceAbility的生命周期方法,添加其他Ability请求与ServiceAbility交互时的处理方法。
7
8   ```ts
9     import rpc from "@ohos.rpc"
10
11     class FirstServiceAbilityStub extends rpc.RemoteObject {
12       constructor(des: any) {
13         if (typeof des === 'string') {
14           super(des)
15         } else {
16           return
17         }
18       }
19     }
20
21     export default {
22       onStart() {
23         console.info('ServiceAbility onStart')
24       },
25       onStop() {
26         console.info('ServiceAbility onStop')
27       },
28       onCommand(want, startId) {
29         console.info('ServiceAbility onCommand')
30       },
31       onConnect(want) {
32         console.info('ServiceAbility onConnect' + want)
33         return new FirstServiceAbilityStub('test')
34       },
35       onDisconnect(want) {
36         console.info('ServiceAbility onDisconnect' + want)
37       }
38     }
39   ```
40
412. 注册ServiceAbility。
42
43    ServiceAbility需要在应用配置文件config.json中进行注册,注册类型type需要设置为service。"visible"属性表示ServiceAbility是否可以被其他应用调用,true表示可以被其他应用调用,false表示不能被其他应用调用(仅应用内可以调用)。若ServiceAbility需要被其他应用调用,注册ServiceAbility时需要设置"visible"为true,同时需要设置支持关联启动。ServiceAbility的启动规则详见[组件启动规则](component-startup-rules.md)章节。
44
45    ```json
46         {
47           "module": {
48             "abilities": [
49               {
50                 "name": ".ServiceAbility",
51                 "srcLanguage": "ets",
52                 "srcPath": "ServiceAbility",
53                 "icon": "$media:icon",
54                 "description": "hap sample empty service",
55                 "type": "service",
56                 "visible": true
57               }
58             ]
59           }
60         }
61    ```
62
63