• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# UIExtensionComponent
2
3UIExtensionComponent用于支持在本页面内嵌入其他应用提供的UI。展示的内容在另外一个进程中运行,本应用并不参与其中的布局和渲染。
4
5通常用于有进程隔离诉求的模块化开发场景。
6
7> **说明:**
8>
9> 该组件从API Version 10开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。
10>
11> 本组件为系统接口。
12
13## 使用约束
14
15本组件不支持预览。
16
17被拉起的Ability必须是带UI的Ability扩展,如何实现带UI的Ability扩展请参考[实现带UI的Ability扩展](../apis/js-apis-app-ability-uiExtensionAbility.md)。
18
19必须显示设置组件宽高为非0有效值。
20
21## 子组件
22
2324
25## 接口
26
27UIExtensionComponent(want: Want)
28
29**参数:**
30
31| 参数名  | 参数类型                                     | 必填   | 参数描述            |
32| ---- | ---------------------------------------- | ---- | --------------- |
33| want | [Want](../apis/js-apis-app-ability-want.md) | 是    | 要加载的Ability。 |
34
35## UIExtensionProxy
36
37用于在双方建立连接成功后,组件使用方向被拉起的Ability发送数据的场景,提供send方法。
38
39### send
40
41send(data: { [key: string]: Object }): void
42
43**参数:**
44
45| 参数名  | 参数类型                                     | 必填   | 参数描述            |
46| ---- | ---------------------------------------- | ---- | --------------- |
47| data | { [key: string]: Object } | 是    | 发送给被拉起的扩展Ability的数据。 |
48
49## 属性
50
51支持[通用属性](ts-universal-attributes-size.md)。
52
53## 事件
54
55不支持[通用事件](ts-universal-events-click.md)。
56
57将事件经过坐标转换后传递给对端Ability处理。
58
59支持以下事件:
60
61### onRemoteReady
62
63onRemoteReady(callback: [Callback](../apis/js-apis-base.md#callback)\<UIExtensionProxy>)
64
65UIExtensionAbility连接完成时的回调,之后可使用proxy向被拉起的Ability发送数据。
66
67**参数:**
68
69| 参数名                       | 类型   | 说明                                                         |
70| ---------------------------- | ------ | ------------------------------------------------------------ |
71| proxy                        | UIExtensionProxy | 用于向对端Ability发送数据。                          |
72
73### onReceive
74
75onReceive(callback: [Callback](../apis/js-apis-base.md#callback)\<{ [key: string]: Object }>)
76
77收到被拉起的Ability发送的数据时触发的回调。
78
79**参数:**
80
81| 参数名                       | 类型   | 说明                                                         |
82| ---------------------------- | ------ | ------------------------------------------------------------ |
83| data                        | { [key: string]: Object } | 收到来自对端Ability的数据。                 |
84
85### onResult
86
87onResult(callback: [Callback](../apis/js-apis-base.md#callback)\<{code: number; want?: Want}>)
88
89被拉起的Ability扩展调用terminateSelfWithResult时会先触发本回调函数,再触发OnRelease。
90
91本回调内可处理对端Ability的结果数据,可参考[AbilityResult](../apis/js-apis-inner-ability-abilityResult.md)。
92
93**参数:**
94
95| 参数名                       | 类型   | 说明                                                         |
96| ---------------------------- | ------ | ------------------------------------------------------------ |
97| code                        | number | 收到来自对端Ability的处理結果code。                          |
98| want                        | Want | 收到来自对端Ability的处理結果[Want](../apis/js-apis-app-ability-want.md)。 |
99
100### onRelease
101
102onRelease(callback: [Callback](../apis/js-apis-base.md#callback)\<number>)
103
104用于处理被拉起的Ability销毁时的回调。
105
106被拉起的Ability扩展调用terminateSelfWithResult或者terminateSelf时会触发本回调,此时releaseCode为0,即正常销毁。
107
108被拉起的Ability扩展意外Crash或被kill时,触发本回调,此时releaseCode为1。
109
110**参数:**
111
112| 参数名                       | 类型   | 说明                                                         |
113| ---------------------------- | ------ | ------------------------------------------------------------ |
114| releaseCode                        | number | 对端Ability销毁时的code,0为正常销毁,1为异常销毁。                          |
115
116### onError
117
118onError(callback:[ErrorCallback](../apis/js-apis-base.md#errorcallback))
119
120被拉起的Ability扩展在运行过程中发生异常时触发本回调。可通过回调参数中的code、name和message获取错误信息并做处理。
121
122**参数:**
123
124| 参数名                       | 类型   | 说明                                                         |
125| ---------------------------- | ------ | ------------------------------------------------------------ |
126| err                        | [BusinessError](../apis/js-apis-base.md#businesserror) | 报错信息。    |
127
128## 示例
129
130本示例仅展示组件使用的方法和扩展的Ability,实际运行需在设备中安装bundleName为"com.example.uiextensionprovider",abilityName为"UIExtensionProvider"的Ability扩展。
131
132```ts
133// 组件使用示例:
134import Want from '@ohos.app.ability.Want';
135
136@Entry
137@Component
138struct Index {
139  @State message: string = 'Hello World'
140  private myProxy: UIExtensionProxy | null = null;
141  want: Want = {
142    bundleName: "com.example.uiextensionprovider",
143    abilityName: "UIExtensionProvider",
144    parameters: { "x": 12345, "y": "data" }
145  }
146
147  build() {
148    Row() {
149      Column() {
150        Text(this.message).fontColor(Color.Red)
151        UIExtensionComponent(this.want)
152          .size({ width: "100%", height: "100%" })
153          .onRemoteReady((proxy: UIExtensionProxy) => {
154            this.message = "remote ready"
155            this.myProxy = proxy
156          })
157          .onReceive((data: Object) => {
158            this.message = JSON.stringify(data)
159          })
160          .onRelease((releaseCode: number) => {
161            this.message = "Release: " + releaseCode
162          })
163          .onResult((data: Object) => {
164            this.message = JSON.stringify(data)
165          })
166          .onError((error: ErrorObject) => {
167            this.message = "onError: " + error.code + ", name: " + error.name + ", message: " + error.message
168          })
169        Button("sendData").onClick(() => {
170          if (this.myProxy != null) {
171            let a: Record<string, number> = { "x": 5678910 };
172            this.myProxy.send(a)
173          }
174        })
175      }
176      .width("100%")
177    }
178    .height('100%')
179  }
180}
181
182interface ErrorObject {
183  code: number;
184  name: string;
185  message: string;
186}
187```
188
189```ts
190// 扩展入口文件UIExtensionProvider.ts
191import UIExtensionAbility from '@ohos.app.ability.UIExtensionAbility'
192import UIExtensionContentSession from '@ohos.app.ability.UIExtensionContentSession'
193import Want from '@ohos.app.ability.Want';
194const TAG: string = '[UIExtAbility]'
195export default class UIExtAbility extends UIExtensionAbility {
196  onCreate() {
197    console.log(TAG, `UIExtAbility onCreate`)
198  }
199
200  onForeground() {
201    console.log(TAG, `UIExtAbility onForeground`)
202  }
203
204  onBackground() {
205    console.log(TAG, `UIExtAbility onBackground`)
206  }
207
208  onDestroy() {
209    console.log(TAG, `UIExtAbility onDestroy`)
210  }
211
212  onSessionCreate(want: Want, session: UIExtensionContentSession) {
213    console.log(TAG, `UIExtAbility onSessionCreate, want: ${JSON.stringify(want)}`)
214    let param: Record<string, UIExtensionContentSession> = {
215      'session': session
216    }
217    let storage: LocalStorage = new LocalStorage(param);
218    session.loadContent('pages/extension', storage);
219  }
220
221  onSessionDestroy(session: UIExtensionContentSession) {
222    console.log(TAG, `UIExtAbility onSessionDestroy`)
223  }
224}
225```
226
227```ts
228// 扩展Ability入口页面文件extension.ets
229import UIExtensionContentSession from '@ohos.app.ability.UIExtensionContentSession'
230
231let storage = LocalStorage.GetShared()
232
233@Entry(storage)
234@Component
235struct Index {
236  @State message: string = 'UIExtension'
237  @State message2: string = 'message from comp'
238  private session: UIExtensionContentSession | undefined = storage.get<UIExtensionContentSession>('session');
239  controller: TextInputController = new TextInputController()
240
241  onPageShow() {
242    if (this.session != undefined) {
243      this.session.setReceiveDataCallback((data: Object) => {
244        this.message2 = "data come from comp"
245        this.message = JSON.stringify(data)
246      })
247    }
248  }
249
250  build() {
251    Row() {
252      Column() {
253        Text(this.message2)
254        Text(this.message)
255        Button("sendData")
256          .onClick(() => {
257            if (this.session != undefined) {
258              let a: Record<string, string> = {"xxx": "data from extension"};
259              this.session.sendData(a)
260            }
261          })
262        Button("terminateSelf")
263          .onClick(() => {
264            if (this.session != undefined) {
265              this.session.terminateSelf();
266              storage.clear();
267            }
268          }).margin(5)
269        Button("TerminateSelfWithResult")
270          .onClick(() => {
271            if (this.session != undefined) {
272              this.session.terminateSelfWithResult({
273                "resultCode": 0,
274                "want": {
275                  "bundleName": "myName"
276                }
277              });
278              storage.clear();
279            }
280          }).margin(5)
281      }
282      .width('100%')
283    }
284    .height('100%')
285  }
286}
287```
288