HarmonyOS鸿蒙Next中展示多个页面,如何在某个页面进行消息发送,所有展示的页面均接收到发送的消息

HarmonyOS鸿蒙Next中展示多个页面,如何在某个页面进行消息发送,所有展示的页面均接收到发送的消息

3 回复

在同进程中跨线程可以使用emitter,emitter提供了在同一进程不同线程间,或同一进程同一线程内,发送和处理事件的能力。

链接如下: https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V5/js-apis-emitter-V5

不同进程可采用动态订阅公共事件,用法和android动态广播类似,

参考链接: https://developer.huawei.com/consumer/cn/doc/harmonyos-guides-V5/common-event-subscription-V5

更多关于HarmonyOS鸿蒙Next中展示多个页面,如何在某个页面进行消息发送,所有展示的页面均接收到发送的消息的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


在HarmonyOS Next中,要实现跨页面消息通信,可以使用EventHub或Emitter。EventHub是Ability提供的消息中心,通过订阅和发布实现通信。在发送页面调用eventHub.emit("eventName", data),在其他页面提前用eventHub.on("eventName", callback)订阅即可。Emitter是进程内通信机制,使用emit发送,on接收。两者都支持一对多消息传递,区别在于EventHub适用于Ability内,Emitter适用于进程内组件间通信。注意消息类型需保持一致。

在HarmonyOS Next中实现跨页面消息通信,可以使用EventHub或UIAbilityContext的事件机制。以下是两种实现方式:

  1. 使用EventHub:
// 发送消息的页面
import common from '@ohos.app.ability.common';

let eventHub = getContext(this)?.eventHub;
eventHub?.emit('myEvent', {data: '消息内容'});

// 接收消息的页面(每个页面都需要注册监听)
let eventHub = getContext(this)?.eventHub;
eventHub?.on('myEvent', (data) => {
  console.log('收到消息:', data);
});
  1. 使用UIAbilityContext(适用于不同Ability间通信):
// 发送方
let abilityContext = getContext(this) as common.UIAbilityContext;
abilityContext.emit('globalEvent', {data: '消息内容'});

// 接收方(每个页面)
let abilityContext = getContext(this) as common.UIAbilityContext;
abilityContext.on('globalEvent', (data) => {
  console.log('收到全局消息:', data);
});

注意事项:

  • EventHub适合同一Ability内页面通信
  • UIAbilityContext支持跨Ability通信
  • 页面销毁时需要取消事件监听
  • 大数据传输建议使用其他机制
回到顶部