1# @ohos.app.ability.sendableContextManager (sendableContextManager)
2
3sendableContextManager模块提供Context与[SendableContext](js-apis-inner-application-sendableContext.md)相互转换的能力。
4
5> **说明:**
6>
7> - 本模块首批接口从API version 12 开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
8> - 本模块接口仅可在Stage模型下使用。
9
10## 使用场景
11
12本模块主要用于ArkTS并发实例间(包括主线程、TaskPool&Worker工作线程)的数据传递。
13
14例如,以主线程向子线程传递Sendable数据,转换过程如下:
15- 主线程向子线程传递Sendable数据时,需要将Context转换为SendableContext。
16- 子线程使用Sendable数据时,需要将SendableContext转换为Context。
17
18这里的Context与[createModuleContext](./js-apis-app-ability-application.md#applicationcreatemodulecontext12)方法创建的Context不同,具体差异如下:
19- 与SendableContext相互转换的Context:ArkTS并发实例持有的应用侧Context是不同的实例,底层对应同一个Context对象。当一个实例中Context属性和方法被修改时,相关实例中的Context属性和方法将会同步修改。其中,Context实例中的eventHub属性比较特殊,不同实例中的eventHub是独立的对象,不支持跨ArkTS实例使用。
20- 通过[createModuleContext](./js-apis-app-ability-application.md#applicationcreatemodulecontext12)创建的Context:ArkTS并发实例持有的应用侧Context是不同的实例,底层对应不同的Context对象。
21
22## 约束限制
23
24“Context转换为SendableContext”和“SendableContext转换为Context”两个环节中的Context类型必须保持一致。目前支持转换的Context包括[Context](js-apis-inner-application-context.md)、[ApplicationContext](js-apis-inner-application-applicationContext.md)、[AbilityStageContext](js-apis-inner-application-abilityStageContext.md)、[UIAbilityContext](js-apis-inner-application-uiAbilityContext.md)。
25
26## 导入模块
27
28```ts
29import { sendableContextManager } from '@kit.AbilityKit';
30```
31
32## 属性
33
34**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
35
36**原子化服务API**:从API version 12开始,该接口支持在原子化服务中使用。
37
38| 名称 | 类型 | 必填 | 说明 |
39| ------- | ------- | ------- | ------- |
40| SendableContext | [SendableContext](js-apis-inner-application-sendableContext.md) | 是 | SendableContext二级模块。 |
41
42**示例:**
43
44```ts
45import { sendableContextManager } from '@kit.AbilityKit';
46
47let sendableContext: sendableContextManager.SendableContext;
48```
49
50## sendableContextManager.convertFromContext
51
52convertFromContext(context: common.Context): SendableContext;
53
54将Context转换为SendableContext对象。
55
56**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
57
58**原子化服务API**:从API version 12开始,该接口支持在原子化服务中使用。
59
60**参数:**
61
62| 参数名 | 类型 | 必填 | 说明 |
63| ------- | ------- | ------- | ------- |
64| context | common.Context | 是 | Context对象,支持Context基类,ApplicationContext、AbilityStageContext和UIAbilityContext子类。 |
65
66**错误码**:
67
68以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)。
69
70| 错误码ID | 错误信息 |
71| ------- | ------- |
72| 401     | If the input parameter invalid. Possible causes: 1.Incorrect parameter types; 2.Parameter verification failed. |
73
74**示例:**
75
76```ts
77import { AbilityConstant, UIAbility, Want, sendableContextManager } from '@kit.AbilityKit';
78import { hilog } from '@kit.PerformanceAnalysisKit';
79import { worker } from '@kit.ArkTS';
80
81@Sendable
82export class SendableObject {
83  constructor(sendableContext: sendableContextManager.SendableContext) {
84    this.sendableContext = sendableContext;
85  }
86
87  sendableContext: sendableContextManager.SendableContext;
88  // other sendable object
89}
90
91export default class EntryAbility extends UIAbility {
92  worker: worker.ThreadWorker = new worker.ThreadWorker('entry/ets/workers/Worker.ets');
93
94  onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void {
95    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onCreate');
96
97    // convert and post
98    try {
99      let sendableContext: sendableContextManager.SendableContext = sendableContextManager.convertFromContext(this.context);
100      let object: SendableObject = new SendableObject(sendableContext);
101      hilog.info(0x0000, 'testTag', '%{public}s', 'Ability post message');
102      this.worker.postMessageWithSharedSendable(object);
103    } catch (error) {
104      hilog.error(0x0000, 'testTag', 'convertFromContext failed %{public}s', JSON.stringify(error));
105    }
106  }
107}
108```
109
110## sendableContextManager.convertToContext
111
112convertToContext(sendableContext: SendableContext): common.Context
113
114将SendableContext对象转换为Context。
115
116**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
117
118**原子化服务API**:从API version 12开始,该接口支持在原子化服务中使用。
119
120**参数:**
121
122| 参数名 | 类型 | 必填 | 说明 |
123| ------- | ------- | ------- | ------- |
124| sendableContext | [SendableContext](js-apis-inner-application-sendableContext.md) | 是 | SendableContext对象。 |
125
126**错误码**:
127
128以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)。
129
130| 错误码ID | 错误信息 |
131| ------- | ------- |
132| 401     | If the input parameter invalid. Possible causes: 1.Incorrect parameter types; 2.Parameter verification failed. |
133
134**示例:**
135
136主线程传递Context:
137```ts
138import { AbilityConstant, UIAbility, Want, common, sendableContextManager } from '@kit.AbilityKit';
139import { hilog } from '@kit.PerformanceAnalysisKit';
140import { worker } from '@kit.ArkTS';
141
142@Sendable
143export class SendableObject {
144  constructor(sendableContext: sendableContextManager.SendableContext, contextName: string) {
145    this.sendableContext = sendableContext;
146    this.contextName = contextName;
147  }
148
149  sendableContext: sendableContextManager.SendableContext;
150  contextName: string;
151}
152
153export default class EntryAbility extends UIAbility {
154  worker: worker.ThreadWorker = new worker.ThreadWorker('entry/ets/workers/Worker.ets');
155
156  onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void {
157    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onCreate');
158
159    // convert and post
160    try {
161      let context: common.Context = this.context as common.Context;
162      let sendableContext: sendableContextManager.SendableContext = sendableContextManager.convertFromContext(context);
163      let object: SendableObject = new SendableObject(sendableContext, 'BaseContext');
164      hilog.info(0x0000, 'testTag', '%{public}s', 'Ability post message');
165      this.worker.postMessageWithSharedSendable(object);
166    } catch (error) {
167      hilog.error(0x0000, 'testTag', 'convertFromContext failed %{public}s', JSON.stringify(error));
168    }
169  }
170}
171```
172
173Worker线程接收Context:
174```ts
175import { ErrorEvent, MessageEvents, ThreadWorkerGlobalScope, worker } from '@kit.ArkTS';
176import { common, sendableContextManager } from '@kit.AbilityKit';
177import { hilog } from '@kit.PerformanceAnalysisKit';
178
179@Sendable
180export class SendableObject {
181  constructor(sendableContext: sendableContextManager.SendableContext, contextName: string) {
182    this.sendableContext = sendableContext;
183    this.contextName = contextName;
184  }
185
186  sendableContext: sendableContextManager.SendableContext;
187  contextName: string;
188}
189
190const workerPort: ThreadWorkerGlobalScope = worker.workerPort;
191
192workerPort.onmessage = (e: MessageEvents) => {
193  let object: SendableObject = e.data;
194  let sendableContext: sendableContextManager.SendableContext = object.sendableContext;
195  if (object.contextName == 'BaseContext') {
196    hilog.info(0x0000, 'testTag', '%{public}s', 'convert to context.');
197    try {
198      let context: common.Context = sendableContextManager.convertToContext(sendableContext);
199      // 获取context后获取沙箱路径
200      hilog.info(0x0000, 'testTag', 'worker context.databaseDir: %{public}s', context.databaseDir);
201    } catch (error) {
202      hilog.error(0x0000, 'testTag', 'convertToContext failed %{public}s', JSON.stringify(error));
203    }
204  }
205}
206
207workerPort.onmessageerror = (e: MessageEvents) => {
208  hilog.info(0x0000, 'testTag', '%{public}s', 'onmessageerror');
209}
210
211workerPort.onerror = (e: ErrorEvent) => {
212  hilog.info(0x0000, 'testTag', '%{public}s', 'onerror');
213}
214```
215
216## sendableContextManager.convertToApplicationContext
217
218convertToApplicationContext(sendableContext: SendableContext): common.ApplicationContext
219
220将SendableContext对象转换为ApplicationContext。
221
222**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
223
224**原子化服务API**:从API version 12开始,该接口支持在原子化服务中使用。
225
226**参数:**
227
228| 参数名 | 类型 | 必填 | 说明 |
229| ------- | ------- | ------- | ------- |
230| sendableContext | [SendableContext](js-apis-inner-application-sendableContext.md) | 是 | SendableContext对象。 |
231
232**错误码**:
233
234以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)。
235
236| 错误码ID | 错误信息 |
237| ------- | ------- |
238| 401     | If the input parameter invalid. Possible causes: 1.Incorrect parameter types; 2.Parameter verification failed. |
239
240**示例:**
241
242主线程传递Context:
243```ts
244import { AbilityConstant, UIAbility, Want, common, sendableContextManager } from '@kit.AbilityKit';
245import { hilog } from '@kit.PerformanceAnalysisKit';
246import { worker } from '@kit.ArkTS';
247
248@Sendable
249export class SendableObject {
250  constructor(sendableContext: sendableContextManager.SendableContext, contextName: string) {
251    this.sendableContext = sendableContext;
252    this.contextName = contextName;
253  }
254
255  sendableContext: sendableContextManager.SendableContext;
256  contextName: string;
257}
258
259export default class EntryAbility extends UIAbility {
260  worker: worker.ThreadWorker = new worker.ThreadWorker('entry/ets/workers/Worker.ets');
261
262  onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void {
263    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onCreate');
264
265    // convert and post
266    try {
267      let context: common.Context = this.context as common.Context;
268      let applicationContext = context.getApplicationContext();
269      let sendableContext: sendableContextManager.SendableContext = sendableContextManager.convertFromContext(applicationContext);
270      let object: SendableObject = new SendableObject(sendableContext, 'ApplicationContext');
271      hilog.info(0x0000, 'testTag', '%{public}s', 'Ability post message');
272      this.worker.postMessageWithSharedSendable(object);
273    } catch (error) {
274      hilog.error(0x0000, 'testTag', 'convertFromContext failed %{public}s', JSON.stringify(error));
275    }
276  }
277}
278```
279
280Worker线程接收Context:
281```ts
282import { ErrorEvent, MessageEvents, ThreadWorkerGlobalScope, worker } from '@kit.ArkTS';
283import { common, sendableContextManager } from '@kit.AbilityKit';
284import { hilog } from '@kit.PerformanceAnalysisKit';
285
286@Sendable
287export class SendableObject {
288  constructor(sendableContext: sendableContextManager.SendableContext, contextName: string) {
289    this.sendableContext = sendableContext;
290    this.contextName = contextName;
291  }
292
293  sendableContext: sendableContextManager.SendableContext;
294  contextName: string;
295}
296
297const workerPort: ThreadWorkerGlobalScope = worker.workerPort;
298
299workerPort.onmessage = (e: MessageEvents) => {
300  let object: SendableObject = e.data;
301  let sendableContext: sendableContextManager.SendableContext = object.sendableContext;
302  if (object.contextName == 'ApplicationContext') {
303    hilog.info(0x0000, 'testTag', '%{public}s', 'convert to application context.');
304    try {
305      let context: common.ApplicationContext = sendableContextManager.convertToApplicationContext(sendableContext);
306      // 获取context后获取沙箱路径
307      hilog.info(0x0000, 'testTag', 'worker context.databaseDir: %{public}s', context.databaseDir);
308    } catch (error) {
309      hilog.error(0x0000, 'testTag', 'convertToApplicationContext failed %{public}s', JSON.stringify(error));
310    }
311  }
312}
313
314workerPort.onmessageerror = (e: MessageEvents) => {
315  hilog.info(0x0000, 'testTag', '%{public}s', 'onmessageerror');
316}
317
318workerPort.onerror = (e: ErrorEvent) => {
319  hilog.info(0x0000, 'testTag', '%{public}s', 'onerror');
320}
321```
322
323## sendableContextManager.convertToAbilityStageContext
324
325convertToAbilityStageContext(sendableContext: SendableContext): common.AbilityStageContext
326
327将SendableContext对象转换为AbilityStageContext。
328
329**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
330
331**原子化服务API**:从API version 12开始,该接口支持在原子化服务中使用。
332
333**参数:**
334
335| 参数名 | 类型 | 必填 | 说明 |
336| ------- | ------- | ------- | ------- |
337| sendableContext | [SendableContext](js-apis-inner-application-sendableContext.md) | 是 | SendableContext对象。 |
338
339**错误码**:
340
341以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)。
342
343| 错误码ID | 错误信息 |
344| ------- | ------- |
345| 401     | If the input parameter invalid. Possible causes: 1.Incorrect parameter types; 2.Parameter verification failed. |
346
347**示例:**
348
349主线程传递Context:
350```ts
351import { UIAbility, sendableContextManager } from '@kit.AbilityKit';
352import { hilog } from '@kit.PerformanceAnalysisKit';
353import { worker } from '@kit.ArkTS';
354
355@Sendable
356export class SendableObject {
357  constructor(sendableContext: sendableContextManager.SendableContext, contextName: string) {
358    this.sendableContext = sendableContext;
359    this.contextName = contextName;
360  }
361
362  sendableContext: sendableContextManager.SendableContext;
363  contextName: string;
364}
365
366export default class EntryAbility extends UIAbility {
367  worker: worker.ThreadWorker = new worker.ThreadWorker('entry/ets/workers/Worker.ets');
368
369  onCreate(): void {
370    hilog.info(0x0000, 'testTag', '%{public}s', 'AbilityStage onCreate');
371
372    // convert and post
373    try {
374      let sendableContext: sendableContextManager.SendableContext = sendableContextManager.convertFromContext(this.context);
375      let object: SendableObject = new SendableObject(sendableContext, 'AbilityStageContext');
376      hilog.info(0x0000, 'testTag', '%{public}s', 'AbilityStage post message');
377      this.worker.postMessageWithSharedSendable(object);
378    } catch (error) {
379      hilog.error(0x0000, 'testTag', 'convertFromContext failed %{public}s', JSON.stringify(error));
380    }
381  }
382}
383```
384
385Worker线程接收Context:
386```ts
387import { ErrorEvent, MessageEvents, ThreadWorkerGlobalScope, worker } from '@kit.ArkTS';
388import { common, sendableContextManager } from '@kit.AbilityKit';
389import { hilog } from '@kit.PerformanceAnalysisKit';
390
391@Sendable
392export class SendableObject {
393  constructor(sendableContext: sendableContextManager.SendableContext, contextName: string) {
394    this.sendableContext = sendableContext;
395    this.contextName = contextName;
396  }
397
398  sendableContext: sendableContextManager.SendableContext;
399  contextName: string;
400}
401
402const workerPort: ThreadWorkerGlobalScope = worker.workerPort;
403
404workerPort.onmessage = (e: MessageEvents) => {
405  let object: SendableObject = e.data;
406  let sendableContext: sendableContextManager.SendableContext = object.sendableContext;
407  if (object.contextName == 'AbilityStageContext') {
408    hilog.info(0x0000, 'testTag', '%{public}s', 'convert to abilitystage context.');
409    try {
410      let context: common.AbilityStageContext = sendableContextManager.convertToAbilityStageContext(sendableContext);
411      // 获取context后获取沙箱路径
412      hilog.info(0x0000, 'testTag', 'worker context.databaseDir: %{public}s', context.databaseDir);
413    } catch (error) {
414      hilog.error(0x0000, 'testTag', 'convertToAbilityStageContext failed %{public}s', JSON.stringify(error));
415    }
416  }
417}
418
419workerPort.onmessageerror = (e: MessageEvents) => {
420  hilog.info(0x0000, 'testTag', '%{public}s', 'onmessageerror');
421}
422
423workerPort.onerror = (e: ErrorEvent) => {
424  hilog.info(0x0000, 'testTag', '%{public}s', 'onerror');
425}
426```
427
428## sendableContextManager.convertToUIAbilityContext
429
430convertToUIAbilityContext(sendableContext: SendableContext): common.UIAbilityContext
431
432将SendableContext对象转换为UIAbilityContext。
433
434**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
435
436**原子化服务API**:从API version 12开始,该接口支持在原子化服务中使用。
437
438**参数:**
439
440| 参数名 | 类型 | 必填 | 说明 |
441| ------- | ------- | ------- | ------- |
442| sendableContext | [SendableContext](js-apis-inner-application-sendableContext.md) | 是 | SendableContext对象。 |
443
444**错误码**:
445
446以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)。
447
448| 错误码ID | 错误信息 |
449| ------- | ------- |
450| 401     | If the input parameter invalid. Possible causes: 1.Incorrect parameter types; 2.Parameter verification failed. |
451
452**示例:**
453
454主线程传递Context:
455```ts
456import { AbilityConstant, UIAbility, Want, common, sendableContextManager } from '@kit.AbilityKit';
457import { hilog } from '@kit.PerformanceAnalysisKit';
458import { worker } from '@kit.ArkTS';
459
460@Sendable
461export class SendableObject {
462  constructor(sendableContext: sendableContextManager.SendableContext, contextName: string) {
463    this.sendableContext = sendableContext;
464    this.contextName = contextName;
465  }
466
467  sendableContext: sendableContextManager.SendableContext;
468  contextName: string;
469}
470
471export default class EntryAbility extends UIAbility {
472  worker: worker.ThreadWorker = new worker.ThreadWorker('entry/ets/workers/Worker.ets');
473
474  onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void {
475    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onCreate');
476
477    // convert and post
478    try {
479      let sendableContext: sendableContextManager.SendableContext = sendableContextManager.convertFromContext(this.context);
480      let object: SendableObject = new SendableObject(sendableContext, 'EntryAbilityContext');
481      hilog.info(0x0000, 'testTag', '%{public}s', 'Ability post message');
482      this.worker.postMessageWithSharedSendable(object);
483    } catch (error) {
484      hilog.error(0x0000, 'testTag', 'convertFromContext failed %{public}s', JSON.stringify(error));
485    }
486  }
487}
488```
489
490Worker线程接收Context:
491```ts
492import { ErrorEvent, MessageEvents, ThreadWorkerGlobalScope, worker } from '@kit.ArkTS';
493import { common, sendableContextManager } from '@kit.AbilityKit';
494import { hilog } from '@kit.PerformanceAnalysisKit';
495
496@Sendable
497export class SendableObject {
498  constructor(sendableContext: sendableContextManager.SendableContext, contextName: string) {
499    this.sendableContext = sendableContext;
500    this.contextName = contextName;
501  }
502
503  sendableContext: sendableContextManager.SendableContext;
504  contextName: string;
505}
506
507const workerPort: ThreadWorkerGlobalScope = worker.workerPort;
508
509workerPort.onmessage = (e: MessageEvents) => {
510  let object: SendableObject = e.data;
511  let sendableContext: sendableContextManager.SendableContext = object.sendableContext;
512  if (object.contextName == 'EntryAbilityContext') {
513    hilog.info(0x0000, 'testTag', '%{public}s', 'convert to uiability context.');
514    try {
515      let context: common.UIAbilityContext = sendableContextManager.convertToUIAbilityContext(sendableContext);
516      // 获取context后获取沙箱路径
517      hilog.info(0x0000, 'testTag', 'worker context.databaseDir: %{public}s', context.databaseDir);
518    } catch (error) {
519      hilog.error(0x0000, 'testTag', 'convertToUIAbilityContext failed %{public}s', JSON.stringify(error));
520    }
521  }
522}
523
524workerPort.onmessageerror = (e: MessageEvents) => {
525  hilog.info(0x0000, 'testTag', '%{public}s', 'onmessageerror');
526}
527
528workerPort.onerror = (e: ErrorEvent) => {
529  hilog.info(0x0000, 'testTag', '%{public}s', 'onerror');
530}
531```
532