HarmonyOS鸿蒙NEXT中PC端应用如何使用自定义公共事件实现进程间通信的示例?
HarmonyOS鸿蒙NEXT中PC端应用如何使用自定义公共事件实现进程间通信的示例? 要实现通过发布和订阅自定义公共事件实现在两个应用之间的通信,如何使用@ohos.commonEventManager来开发,有相关的demo可以参考吗?
参考文档:自定义公共事件实现进程间通信
更多关于HarmonyOS鸿蒙NEXT中PC端应用如何使用自定义公共事件实现进程间通信的示例?的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html
在HarmonyOS NEXT的PC端应用中,可通过自定义公共事件实现进程间通信。首先,在module.json5文件中声明自定义事件,例如"events": ["my_custom_event"]。然后,使用emit方法发布事件,如EventHub.emit("my_custom_event", data)。其他进程通过on方法订阅该事件接收数据,如EventHub.on("my_custom_event", callback)。需确保事件名称一致,且发布和订阅方在同一设备上运行。
在HarmonyOS NEXT中,使用@ohos.commonEventManager实现PC端应用间的自定义公共事件通信,核心步骤包括发布事件和订阅事件。以下是关键代码示例:
1. 订阅自定义事件
在接收方应用中,订阅指定自定义事件(例如:"my_custom_event"):
import commonEventManager from '@ohos.commonEventManager';
import { BusinessError } from '@ohos.base';
// 订阅自定义公共事件
commonEventManager.createSubscriber(
{
events: ["my_custom_event"] // 自定义事件名称
},
(err: BusinessError, subscriber: commonEventManager.CommonEventSubscriber) => {
if (err) {
console.error(`Failed to create subscriber. Code: ${err.code}, message: ${err.message}`);
return;
}
// 订阅回调
commonEventManager.subscribe(
subscriber,
(err: BusinessError, data: commonEventManager.CommonEventData) => {
if (err) {
console.error(`Failed to subscribe. Code: ${err.code}, message: ${err.message}`);
return;
}
console.info(`Received custom event: ${JSON.stringify(data)}`);
// 处理接收到的数据
}
);
}
);
2. 发布自定义事件 在发送方应用中,发布携带数据的自定义事件:
import commonEventManager from '@ohos.commonEventManager';
import { BusinessError } from '@ohos.base';
// 发布自定义公共事件
commonEventManager.publish(
"my_custom_event", // 与订阅方一致的事件名称
{
code: 0, // 结果码(可选)
data: "This is custom event data", // 自定义数据
// 可附加其他参数
},
(err: BusinessError) => {
if (err) {
console.error(`Failed to publish event. Code: ${err.code}, message: ${err.message}`);
return;
}
console.info("Custom event published successfully.");
}
);
关键配置
- 在
module.json5中为两个应用分别声明ohos.permission.COMMONEVENT_STICKY权限(仅用于粘性事件,普通事件可不声明)。 - 确保发布和订阅的事件名称完全一致(如示例中的
"my_custom_event")。 - 事件数据通过
publish方法的第二个参数传递,订阅方在回调的data字段中获取。
注意事项
- 普通事件在发布时若无活跃订阅者则会丢弃;粘性事件会持续留存至被消费。
- 进程间通信需确保应用已正确安装并授权。
- 完整示例可参考官方文档中“CommonEvent”相关章节,或通过DevEco Studio模板创建事件通信样例工程。
此方案适用于同一设备上应用间的松耦合通信,无需直接绑定进程即可实现数据交换。

