1# UIServiceExtensionConnectCallback
2
3UIServiceExtensionConnectCallback provides callbacks for the connection to a UIServiceExtensionAbility.
4
5
6> **NOTE**
7>
8>  - The initial APIs of this module are supported since API version 13. Newly added APIs will be marked with a superscript to indicate their earliest API version.
9>  - The APIs of this module can be used only in the stage model.
10>  - The APIs of this module must be used in the main thread, but not in sub-threads such as Worker and TaskPool.
11
12## Modules to Import
13
14```ts
15import { common } from '@kit.AbilityKit';
16```
17
18## UIServiceExtensionConnectCallback.onData
19
20 onData(data: Record<string, Object>): void
21
22Called to receive data when a connection to the UIServiceExtensionAbility is established.
23
24> **NOTE**
25>
26> For details about the startup rules for the components in the stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md).
27>
28
29
30**System capability**: SystemCapability.Ability.AbilityRuntime.Core
31
32**Parameters**
33
34| Name| Type                  | Read Only| Optional| Description        |
35| ------ | ---------------------- | ---- | ------------ | ------------ |
36| data   | Record<string, Object> | Yes| No | Data about the UIServiceExtensionAbility connection.|
37
38
39**Example**
40
41```ts
42import { common } from '@kit.AbilityKit';
43import { BusinessError } from '@kit.BasicServicesKit';
44
45const TAG: string = '[Extension] ';
46
47@Entry
48@Component
49struct UIServiceExtensionAbility {
50  comProxy: common.UIServiceProxy | null = null;
51  dataCallBack: common.UIServiceExtensionConnectCallback = {
52    onData: (data: Record<string, Object>) => {
53      console.log(TAG + `dataCallBack received data: `, JSON.stringify(data));
54    },
55    onDisconnect: () => {
56      console.log(TAG + `dataCallBack onDisconnect`);
57      this.comProxy = null;
58    }
59  }
60
61  build() {
62    Scroll() {
63      Column() {
64        // Create a button for connecting to the UIServiceExtensionAbility.
65        Button('connectUIServiceExtensionAbility', { type: ButtonType.Capsule, stateEffect: true })
66          .margin({
67            top: 5,
68            left: 10,
69            right: 10,
70            bottom: 5
71          })
72          .alignRules({
73            center: { anchor: '__container__', align: VerticalAlign.Center },
74            middle: { anchor: '__container__', align: HorizontalAlign.Center }
75          })
76          .onClick(() => {
77            this.myConnectUIServiceExtensionAbility()
78          });
79      }
80      .width('100%')
81    }
82    .height('100%')
83  }
84
85  myConnectUIServiceExtensionAbility() {
86    // Obtain the context.
87    let context = getContext(this) as common.UIAbilityContext;
88    let startWant: Want = {
89      deviceId: '',
90      bundleName: 'com.acts.myapplication',
91      abilityName: 'UiServiceExtensionAbility'
92    };
93
94    try {
95      // Connect to the UIServiceExtensionAbility.
96      context.connectUIServiceExtensionAbility(startWant, this.dataCallBack)
97        .then((proxy: common.UIServiceProxy) => {
98          console.log(TAG + `try to connectUIServiceExtensionAbility ${proxy}}`);
99          this.comProxy = proxy;
100          let formData: Record<string,string> = {
101            'PATH': '/tmp/aaa.jpg'
102          };
103          try {
104            console.log(TAG + `sendData`);
105            this.comProxy.sendData(formData);
106          } catch (err) {
107            let code = (err as BusinessError).code;
108            let message = (err as BusinessError).message;
109            console.log(TAG + `sendData failed, code is ${code}, message is ${message}`);
110          }
111        }).catch((err: Error) => {
112        let code = (err as BusinessError).code;
113        let message = (err as BusinessError).message;
114        console.log(TAG + `connectUIServiceExtensionAbility failed, code is ${code}, message is ${message}`);
115      });
116    } catch (err) {
117      let code = (err as BusinessError).code;
118      let message = (err as BusinessError).message;
119      console.log(TAG + `connectUIServiceExtensionAbility failed, code is ${code}, message is ${message}`);
120    }
121  }
122}
123```
124
125## UIServiceExtensionConnectCallback.onDisconnect
126
127onDisconnect(): void
128
129Called when the connection to the UIServiceExtensionAbility is interrupted.
130
131> **NOTE**
132>
133> For details about the startup rules for the components in the stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md).
134>
135
136
137**System capability**: SystemCapability.Ability.AbilityRuntime.Core
138
139**Parameters**
140
141N/A
142
143**Example**
144```ts
145import { common } from '@kit.AbilityKit';
146import { BusinessError } from '@kit.BasicServicesKit';
147
148const TAG: string = '[Extension] ';
149
150@Entry
151@Component
152struct UIServiceExtensionAbility {
153  comProxy: common.UIServiceProxy | null = null;
154  // Callback for the connection.
155  dataCallBack: common.UIServiceExtensionConnectCallback = {
156    onData: (data: Record<string, Object>) => {
157      console.log(TAG + `dataCallBack received data: `, JSON.stringify(data));
158    },
159    onDisconnect: () => {
160      // Callback for the disconnection.
161      console.log(TAG + `dataCallBack onDisconnect`);
162      this.comProxy = null;
163    }
164  }
165
166  build() {
167    Scroll() {
168      Column() {
169        // Create a button for disconnecting from the UIServiceExtensionAbility.
170        Button('disConnectUIServiceExtensionAbility', { type: ButtonType.Capsule, stateEffect: true })
171          .margin({
172            top: 5,
173            left: 10,
174            right: 10,
175            bottom: 5
176          })
177          .alignRules({
178            center: { anchor: '__container__', align: VerticalAlign.Center },
179            middle: { anchor: '__container__', align: HorizontalAlign.Center }
180          })
181          .onClick(() => {
182            this.myConnectUIServiceExtensionAbility()
183          });
184      }
185      .width('100%')
186    }
187    .height('100%')
188  }
189
190  myConnectUIServiceExtensionAbility() {
191    // Obtain the context.
192    let context = getContext(this) as common.UIAbilityContext;
193    // Disconnect from the UIServiceExtensionAbility.
194    try {
195      // this.comProxy is saved when the connection is established.
196      context.disconnectUIServiceExtensionAbility(this.comProxy).then(() => {
197        console.log(TAG + `disconnectUIServiceExtensionAbility success`);
198      }).catch((err: Error) => {
199        let code = (err as BusinessError).code;
200        let message = (err as BusinessError).message;
201        console.log(TAG + `disconnectUIServiceExtensionAbility failed, code is ${code}, message is ${message}`);
202      });
203    } catch (err) {
204      let code = (err as BusinessError).code;
205      let message = (err as BusinessError).message;
206      console.log(TAG + `disconnectUIServiceExtensionAbility failed, code is ${code}, message is ${message}`);
207    }
208  }
209}
210```
211