文档管理中心
我的

您当前正在浏览HarmonyOS最新文档,覆盖已发布的所有API版本,可在API参考中筛选您使用的API版本。详细的版本配套关系请参考版本说明。

指南与API参考API参考系统基础功能Basic Services Kit(基础服务)ArkTS API进程线程通信@ohos.commonEventManager (公共事件模块)

@ohos.commonEventManager (公共事件模块)

Phone12+PC/2in113+Tablet12+TV19+Wearable18+

本模块提供公共事件的发布、订阅、取消订阅等能力。公共事件是一种系统级的事件通知机制,允许应用在系统状态变化(如开机完成、电量变化、屏幕亮灭等)或业务自定义事件发生时,向订阅了该事件的应用发送通知,实现跨组件、跨应用的信息传递。

本模块涉及的关键概念:

  • 无序公共事件:CES在转发公共事件时,不考虑订阅者是否接收到该事件,也不保证订阅者接收到该事件的顺序与其订阅顺序一致。
  • 有序公共事件:CES在转发公共事件时,根据订阅者设置的优先级等级,优先将公共事件发送给优先级较高的订阅者,等待其成功接收该公共事件之后再将事件发送给优先级较低的订阅者。如果有多个订阅者具有相同的优先级,则他们将随机接收到公共事件。
  • 粘性公共事件:能够让订阅者收到在订阅前已经发送的公共事件就是粘性公共事件。普通的公共事件只能在订阅后发送才能收到,而粘性公共事件的特殊性就是可以先发送后订阅,同时也支持先订阅后发送。发送粘性公共事件必须是系统应用或系统服务。

API 组合使用关系说明:

本模块的事件通信遵循三条组合调用链:订阅流、发布流与有序事件流。其中订阅流与发布流通过事件名称关联,发布方与订阅者无需感知对方存在。

订阅流:创建订阅者 → 注册订阅 → 接收事件 → 取消订阅

  1. 配置订阅者信息,声明订阅的事件名称,可选设置订阅优先级、发布方权限与包名。
  2. 通过commonEventManager.createSubscriberSync创建订阅者对象。
  3. 通过commonEventManager.subscribe注册订阅,事件发布时通过回调接收CommonEventData,在回调中处理事件数据。
  4. 不再需要时,通过commonEventManager.unsubscribe取消订阅。

发布流:发布事件(可选携带数据与属性)

  1. 简单发布:通过commonEventManager.publish仅指定事件名发布事件。
  2. 携带数据与属性发布:通过CommonEventPublishData配置code、data、parameters及isOrdered等属性,再调用publish发布。

有序事件流:按优先级顺序投递 + 订阅者协作

  1. 通过CommonEventPublishData将isOrdered设为true,调用publish发布有序事件,事件按订阅者优先级依次投递。
  2. 高优先级订阅者先收到事件,可在回调中通过setCodeAndData等方法修改code与data数据,供后续订阅者接收。
  3. 处理完成后调用finishCommonEvent,触发事件向下一优先级订阅者投递;若需中止后续投递,可调用abortCommonEvent标记事件为中止状态。
说明

本模块首批接口从API version 9开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。

导入模块

收起
自动换行
深色代码主题
复制
  1. import { commonEventManager } from '@kit.BasicServicesKit';

Support

Phone12+PC/2in113+Tablet12+TV19+Wearable18+

系统公共事件是指由系统服务或系统应用发布的事件,订阅这些公共事件需要特定的权限,并使用相应的事件值,详见系统定义的公共事件。

commonEventManager.publish

Phone12+PC/2in113+Tablet12+TV19+Wearable18+

publish(event: string, callback: AsyncCallback<void>): void

发布公共事件。使用callback异步回调。

元服务API: 从API version 11开始,该接口支持在元服务中使用。

系统能力: SystemCapability.Notification.CommonEvent

参数:

展开
参数名 类型 必填 说明
event string 是 表示要发布的公共事件。详见系统定义的公共事件。字符串长度不超过254字节,超出部分会被截断。
callback AsyncCallback<void> 是 回调函数。当公共事件发布成功时,err为undefined;发布失败时,err为错误对象。

错误码:

以下错误码的详细介绍请参见公共事件错误码。

展开
错误码ID 错误信息
1500003

The common event sending frequency too high.

适用版本:20+

1500007 Failed to send the message to the common event service.
1500008 Failed to initialize the common event service.
1500009 Failed to obtain system parameters.

示例:

收起
自动换行
深色代码主题
复制
  1. import { BusinessError } from '@kit.BasicServicesKit';
  2. // 发布公共事件
  3. try {
  4. commonEventManager.publish('event', (err: BusinessError) => {
  5. if (err) {
  6. console.error(`Failed to publish common event. Code is ${err.code}, message is ${err.message}`);
  7. return;
  8. }
  9. console.info(`Succeeded in publishing common event.`);
  10. });
  11. } catch (error) {
  12. let err: BusinessError = error as BusinessError;
  13. console.error(`Failed to publish common event. Code is ${err.code}, message is ${err.message}`);
  14. }

commonEventManager.publish

Phone12+PC/2in113+Tablet12+TV19+Wearable18+

publish(event: string, options: CommonEventPublishData, callback: AsyncCallback<void>): void

发布公共事件。使用callback异步回调。

元服务API: 从API version 11开始,该接口支持在元服务中使用。

系统能力: SystemCapability.Notification.CommonEvent

参数:

展开
参数名 类型 必填 说明
event string 是 表示要发布的公共事件。详见系统定义的公共事件。字符串长度不超过254字节,超出部分会被截断。
options CommonEventPublishData 是 表示发布公共事件的属性。
callback AsyncCallback<void> 是 回调函数。当公共事件发布成功时,err为undefined;发布失败时,err为错误对象。

错误码:

以下错误码的详细介绍请参见公共事件错误码。

展开
错误码ID 错误信息
1500003

The common event sending frequency too high.

适用版本:20+

1500007 Failed to send the message to the common event service.
1500008 Failed to initialize the common event service.
1500009 Failed to obtain system parameters.

示例:

收起
自动换行
深色代码主题
复制
  1. import { BusinessError } from '@kit.BasicServicesKit';
  2. // 公共事件相关信息,以发布有序公共事件为例
  3. let options: commonEventManager.CommonEventPublishData = {
  4. code: 0,
  5. data: 'initial data',
  6. isOrdered: true // 有序公共事件
  7. };
  8. // 发布公共事件
  9. try {
  10. commonEventManager.publish('event', options, (err: BusinessError) => {
  11. if (err) {
  12. console.error(`Failed to publish common event. Code is ${err.code}, message is ${err.message}`);
  13. return;
  14. }
  15. console.info(`Succeeded in publishing common event.`);
  16. });
  17. } catch (error) {
  18. let err: BusinessError = error as BusinessError;
  19. console.error(`Failed to publish common event. Code is ${err.code}, message is ${err.message}`);
  20. }

commonEventManager.createSubscriber

Phone12+PC/2in113+Tablet12+TV19+Wearable18+

createSubscriber(subscribeInfo: CommonEventSubscribeInfo, callback: AsyncCallback<CommonEventSubscriber>): void

创建订阅者。使用callback异步回调。

元服务API: 从API version 11开始,该接口支持在元服务中使用。

系统能力: SystemCapability.Notification.CommonEvent

参数:

展开
参数名 类型 必填 说明
subscribeInfo CommonEventSubscribeInfo 是 表示订阅信息。
callback AsyncCallback<CommonEventSubscriber> 是 回调函数,用于接收创建的订阅者对象。当公共事件订阅者创建成功时,err为undefined,data为创建成功的CommonEventSubscriber订阅者对象;创建失败时,err为错误对象。

错误码:

以下错误码的详细介绍请参见通用错误码。

展开
错误码ID 错误信息
401 Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed.

示例:

收起
自动换行
深色代码主题
复制
  1. import { BusinessError } from '@kit.BasicServicesKit';
  2. // 定义订阅者,用于保存创建成功的订阅者对象,后续使用其完成订阅及取消订阅的动作
  3. let subscriber: commonEventManager.CommonEventSubscriber | null = null;
  4. // 订阅者信息
  5. let subscribeInfo: commonEventManager.CommonEventSubscribeInfo = {
  6. events: ['event']
  7. };
  8. // 创建订阅者
  9. try {
  10. commonEventManager.createSubscriber(subscribeInfo,
  11. (err: BusinessError, commonEventSubscriber: commonEventManager.CommonEventSubscriber) => {
  12. if (!err) {
  13. console.info(`Succeeded in creating subscriber.`);
  14. subscriber = commonEventSubscriber;
  15. return;
  16. }
  17. console.error(`Failed to create subscriber. Code is ${err.code}, message is ${err.message}`);
  18. });
  19. } catch (error) {
  20. let err: BusinessError = error as BusinessError;
  21. console.error(`Failed to create subscriber. Code is ${err.code}, message is ${err.message}`);
  22. }

commonEventManager.createSubscriber

Phone12+PC/2in113+Tablet12+TV19+Wearable18+

createSubscriber(subscribeInfo: CommonEventSubscribeInfo): Promise<CommonEventSubscriber>

创建订阅者。使用Promise异步回调。

元服务API: 从API version 11开始,该接口支持在元服务中使用。

系统能力: SystemCapability.Notification.CommonEvent

参数:

展开
参数名 类型 必填 说明
subscribeInfo CommonEventSubscribeInfo 是 表示订阅信息。

返回值:

展开
类型 说明
Promise<CommonEventSubscriber> Promise对象,返回创建成功的订阅者对象。

错误码:

以下错误码的详细介绍请参见通用错误码。

展开
错误码ID 错误信息
401 Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed.

示例:

收起
自动换行
深色代码主题
复制
  1. import { BusinessError } from '@kit.BasicServicesKit';
  2. // 定义订阅者,用于保存创建成功的订阅者对象,后续使用其完成订阅及取消订阅的动作
  3. let subscriber: commonEventManager.CommonEventSubscriber | null = null;
  4. // 订阅者信息
  5. let subscribeInfo: commonEventManager.CommonEventSubscribeInfo = {
  6. events: ['event']
  7. };
  8. // 创建订阅者
  9. commonEventManager.createSubscriber(subscribeInfo).then((commonEventSubscriber: commonEventManager.CommonEventSubscriber) => {
  10. console.info(`Succeeded in creating subscriber.`);
  11. subscriber = commonEventSubscriber;
  12. }).catch((err: BusinessError) => {
  13. console.error(`Failed to create subscriber. Code is ${err.code}, message is ${err.message}`);
  14. });

commonEventManager.createSubscriberSync10+

Phone12+PC/2in113+Tablet12+TV19+Wearable18+

createSubscriberSync(subscribeInfo: CommonEventSubscribeInfo): CommonEventSubscriber

同步创建订阅者的接口。

元服务API: 从API version 11开始,该接口支持在元服务中使用。

系统能力: SystemCapability.Notification.CommonEvent

参数:

展开
参数名 类型 必填 说明
subscribeInfo CommonEventSubscribeInfo 是 表示订阅信息。

返回值:

展开
类型 说明
CommonEventSubscriber 返回订阅者对象。

错误码:

以下错误码的详细介绍请参见通用错误码。

展开
错误码ID 错误信息
401 Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed.

示例:

收起
自动换行
深色代码主题
复制
  1. import { BusinessError } from '@kit.BasicServicesKit';
  2. // 定义订阅者,用于保存创建成功的订阅者对象,后续使用其完成订阅及取消订阅的动作
  3. let subscriber: commonEventManager.CommonEventSubscriber | null = null;
  4. // 订阅者信息
  5. let subscribeInfo: commonEventManager.CommonEventSubscribeInfo = {
  6. events: ['event']
  7. };
  8. // 创建订阅者
  9. try {
  10. subscriber = commonEventManager.createSubscriberSync(subscribeInfo);
  11. } catch (error) {
  12. let err: BusinessError = error as BusinessError;
  13. console.error(`Failed to create subscriber. Code is ${err.code}, message is ${err.message}`);
  14. }

commonEventManager.subscribe

Phone12+PC/2in113+Tablet12+TV19+Wearable18+

subscribe(subscriber: CommonEventSubscriber, callback: AsyncCallback<CommonEventData>): void

订阅公共事件。使用callback异步回调。

元服务API: 从API version 11开始,该接口支持在元服务中使用。

系统能力: SystemCapability.Notification.CommonEvent

参数:

展开
参数名 类型 必填 说明
subscriber CommonEventSubscriber 是 表示订阅者对象。
callback AsyncCallback<CommonEventData> 是 回调函数。当公共事件订阅成功后,事件触发时通过data返回公共事件数据;订阅失败时,err为错误对象。

错误码:

以下错误码的详细介绍请参见通用错误码和公共事件错误码。

展开
错误码ID 错误信息
801 Capability not supported.
1500007 Failed to send the message to the common event service.
1500008 Failed to initialize the common event service.
1500010

The count of subscriber exceeds system specification.

适用版本:20+

示例:

收起
自动换行
深色代码主题
复制
  1. import { BusinessError } from '@kit.BasicServicesKit';
  2. // 定义订阅者,用于保存创建成功的订阅者对象,后续使用其完成订阅及取消订阅的动作
  3. let subscriber: commonEventManager.CommonEventSubscriber | null = null;
  4. // 订阅者信息
  5. let subscribeInfo: commonEventManager.CommonEventSubscribeInfo = {
  6. events: ['event']
  7. };
  8. // 创建订阅者
  9. try {
  10. commonEventManager.createSubscriber(subscribeInfo,
  11. (err: BusinessError, commonEventSubscriber: commonEventManager.CommonEventSubscriber) => {
  12. if (!err) {
  13. console.info(`Succeeded in creating subscriber.`);
  14. subscriber = commonEventSubscriber;
  15. // 订阅公共事件
  16. try {
  17. commonEventManager.subscribe(subscriber, (err: BusinessError, data: commonEventManager.CommonEventData) => {
  18. if (err) {
  19. console.error(`Failed to subscribe. Code is ${err.code}, message is ${err.message}`);
  20. return;
  21. }
  22. console.info(`Succeeded in subscribing, data is ${JSON.stringify(data)}`);
  23. });
  24. } catch (error) {
  25. let err: BusinessError = error as BusinessError;
  26. console.error(`Failed to subscribe. Code is ${err.code}, message is ${err.message}`);
  27. }
  28. return;
  29. }
  30. console.error(`Failed to create subscriber. Code is ${err.code}, message is ${err.message}`);
  31. });
  32. } catch (error) {
  33. let err: BusinessError = error as BusinessError;
  34. console.error(`Failed to create subscriber. Code is ${err.code}, message is ${err.message}`);
  35. }

commonEventManager.unsubscribe

Phone12+PC/2in113+Tablet12+TV19+Wearable18+

unsubscribe(subscriber: CommonEventSubscriber, callback?: AsyncCallback<void>): void

取消订阅公共事件。使用callback异步回调。

元服务API: 从API version 11开始,该接口支持在元服务中使用。

系统能力: SystemCapability.Notification.CommonEvent

参数:

展开
参数名 类型 必填 说明
subscriber CommonEventSubscriber 是 表示订阅者对象。
callback AsyncCallback<void> 否 回调函数。当取消公共事件订阅成功时,err为undefined;取消失败时,err为错误对象。不传该参数时,默认取消订阅且不返回结果。

错误码:

以下错误码的详细介绍请参见通用错误码和公共事件错误码。

展开
错误码ID 错误信息
401 Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed.
801 Capability not supported.
1500007 Failed to send the message to the common event service.
1500008 Failed to initialize the common event service.

示例:

收起
自动换行
深色代码主题
复制
  1. import { BusinessError } from '@kit.BasicServicesKit';
  2. // 定义订阅者,用于保存创建成功的订阅者对象,后续使用其完成订阅及取消订阅的动作
  3. let subscriber: commonEventManager.CommonEventSubscriber | null = null;
  4. // 订阅者信息
  5. let subscribeInfo: commonEventManager.CommonEventSubscribeInfo = {
  6. events: ['event']
  7. };
  8. // 创建订阅者
  9. try {
  10. commonEventManager.createSubscriber(subscribeInfo,
  11. (err: BusinessError, commonEventSubscriber: commonEventManager.CommonEventSubscriber) => {
  12. if (!err) {
  13. console.info(`Succeeded in creating subscriber.`);
  14. subscriber = commonEventSubscriber;
  15. // 订阅公共事件
  16. try {
  17. commonEventManager.subscribe(subscriber, (err: BusinessError, data: commonEventManager.CommonEventData) => {
  18. if (err) {
  19. console.error(`Failed to subscribe. Code is ${err.code}, message is ${err.message}`);
  20. return;
  21. }
  22. console.info(`Succeeded in subscribing, data is ${JSON.stringify(data)}`);
  23. });
  24. } catch (error) {
  25. let err: BusinessError = error as BusinessError;
  26. console.error(`Failed to subscribe. Code is ${err.code}, message is ${err.message}`);
  27. }
  28. return;
  29. }
  30. console.error(`Failed to create subscriber. Code is ${err.code}, message is ${err.message}`);
  31. });
  32. } catch (error) {
  33. let err: BusinessError = error as BusinessError;
  34. console.error(`Failed to create subscriber. Code is ${err.code}, message is ${err.message}`);
  35. }
  36. // 取消订阅公共事件
  37. // 等待异步接口subscribe执行完毕,开发者根据实际业务选择是否需要添加setTimeout
  38. setTimeout(() => {
  39. try {
  40. commonEventManager.unsubscribe(subscriber, (err: BusinessError) => {
  41. if (err) {
  42. console.error(`Failed to unsubscribe. Code is ${err.code}, message is ${err.message}`);
  43. return;
  44. }
  45. // subscriber不再使用时需要将其置为null,避免内存泄漏
  46. subscriber = null;
  47. console.info(`Succeeded in unsubscribing.`);
  48. });
  49. } catch (error) {
  50. let err: BusinessError = error as BusinessError;
  51. console.error(`Failed to unsubscribe. Code is ${err.code}, message is ${err.message}`);
  52. }
  53. }, 500);

commonEventManager.subscribeToEvent20+

Phone20+PC/2in120+Tablet20+TV20+Wearable20+

subscribeToEvent(subscriber: CommonEventSubscriber, callback: Callback<CommonEventData>): Promise<void>

订阅公共事件,并返回订阅成功或失败信息。使用Promise异步回调。

元服务API: 从API version 20开始,该接口支持在元服务中使用。

系统能力: SystemCapability.Notification.CommonEvent

参数:

展开
参数名 类型 必填 说明
subscriber CommonEventSubscriber 是 表示订阅者对象。
callback Callback<CommonEventData> 是 回调函数,返回公共事件数据。

返回值:

展开
类型 说明
Promise<void> Promise对象,无返回结果。

错误码:

以下错误码的详细介绍请参见通用错误码和公共事件错误码。

展开
错误码ID 错误信息
801 Capability not supported.
1500007 Failed to send the message to the common event service.
1500008 Failed to initialize the common event service.
1500010 The count of subscriber exceeds system specification.

示例:

收起
自动换行
深色代码主题
复制
  1. import { BusinessError } from '@kit.BasicServicesKit';
  2. // 定义订阅者,用于保存创建成功的订阅者对象,后续使用其完成订阅及取消订阅的动作
  3. let subscriber: commonEventManager.CommonEventSubscriber | null = null;
  4. // 订阅者信息
  5. let subscribeInfo: commonEventManager.CommonEventSubscribeInfo = {
  6. events: ['event']
  7. };
  8. // 创建订阅者
  9. try {
  10. commonEventManager.createSubscriber(subscribeInfo,
  11. (err: BusinessError, commonEventSubscriber: commonEventManager.CommonEventSubscriber) => {
  12. if (err) {
  13. console.error(`Failed to create subscriber. Code is ${err.code}, message is ${err.message}`);
  14. } else {
  15. console.info(`Succeeded in creating subscriber.`);
  16. subscriber = commonEventSubscriber;
  17. // 订阅公共事件
  18. try {
  19. commonEventManager.subscribeToEvent(subscriber, (data: commonEventManager.CommonEventData) => {
  20. console.info(`Succeeded to receive common event, data is ${JSON.stringify(data)}`);
  21. }).then(() => {
  22. console.info(`Succeeded in subscribing.`);
  23. }).catch((err: BusinessError) => {
  24. console.error(`Failed to subscribe. Code is ${err.code}, message is ${err.message}`);
  25. });
  26. } catch (error) {
  27. let err: BusinessError = error as BusinessError;
  28. console.error(`Failed to subscribe. Code is ${err.code}, message is ${err.message}`);
  29. }
  30. }
  31. });
  32. } catch (error) {
  33. let err: BusinessError = error as BusinessError;
  34. console.error(`Failed to create subscriber. Code is ${err.code}, message is ${err.message}`);
  35. }

CommonEventData10+

Phone12+PC/2in113+Tablet12+TV19+Wearable18+

type CommonEventData = _CommonEventData

描述公共事件的数据。

元服务API: 从API version 11开始,该接口支持在元服务中使用。

系统能力: SystemCapability.Notification.CommonEvent

展开
类型 说明
_CommonEventData 表示公共事件的数据。

CommonEventSubscriber10+

Phone12+PC/2in113+Tablet12+TV19+Wearable18+

type CommonEventSubscriber = _CommonEventSubscriber

描述公共事件的订阅者。

元服务API: 从API version 11开始,该接口支持在元服务中使用。

系统能力: SystemCapability.Notification.CommonEvent

展开
类型 说明
_CommonEventSubscriber 描述公共事件的订阅者。

CommonEventSubscribeInfo10+

Phone12+PC/2in113+Tablet12+TV19+Wearable18+

type CommonEventSubscribeInfo = _CommonEventSubscribeInfo

描述公共事件订阅者的信息。

元服务API: 从API version 11开始,该接口支持在元服务中使用。

系统能力: SystemCapability.Notification.CommonEvent

展开
类型 说明
_CommonEventSubscribeInfo 用于表示订阅者的信息。

CommonEventPublishData10+

Phone12+PC/2in113+Tablet12+TV19+Wearable18+

type CommonEventPublishData = _CommonEventPublishData

描述公共事件内容和属性。

元服务API: 从API version 11开始,该接口支持在元服务中使用。

系统能力: SystemCapability.Notification.CommonEvent

展开
类型 说明
_CommonEventPublishData 描述公共事件内容和属性。