在鸿蒙Next(HarmonyOS NEXT)中,消息发送功能通常通过Ability间通信或进程内事件机制实现。以下是核心实现方法及代码示例:
一、使用 Ability 间通信(适用于跨应用/跨模块)
通过 Want 对象和 AbilityContext 实现消息传递:
// 发送消息的 Ability
import UIAbility from '@ohos.app.ability.UIAbility';
import Want from '@ohos.app.ability.Want';
export default class SenderAbility extends UIAbility {
onForeground() {
// 构造 Want 对象,指定目标 Ability 和参数
let want: Want = {
bundleName: "com.example.receiver",
abilityName: "ReceiverAbility",
parameters: {
message: "Hello from Sender!"
}
};
// 启动目标 Ability 并传递数据
this.context.startAbility(want).then(() => {
console.log("Message sent successfully");
});
}
}
// 接收消息的 Ability
import UIAbility from '@ohos.app.ability.UIAbility';
export default class ReceiverAbility extends UIAbility {
onCreate(want, launchParam) {
// 从 Want 中提取消息
let message = want?.parameters?.message;
console.log("Received message: " + message);
}
}
二、使用进程内事件总线(同一应用内通信)
通过 Emitter 模块实现组件间消息传递:
// 发送方
import emitter from '@ohos.events.emitter';
// 定义事件
let event = {
eventId: 1, // 自定义事件 ID
priority: emitter.EventPriority.HIGH // 优先级
};
// 发送事件(携带数据)
let eventData = {
data: {
content: "Hello from Emitter!"
}
};
emitter.emit(event, eventData);
// 接收方
import emitter from '@ohos.events.emitter';
// 订阅事件
emitter.on(event, (eventData) => {
console.log("Received: " + eventData.data.content);
});
// 取消订阅(生命周期结束时调用)
// emitter.off(eventId);
三、使用 UI 数据绑定(ArkUI 声明式开发)
通过 @State 和 @Prop 实现父子组件通信:
// 父组件发送数据
@Entry
@Component
struct ParentComponent {
@State message: string = "Hello from Parent";
build() {
Column() {
ChildComponent({ msg: this.message }) // 传递数据
Button("Update Message")
.onClick(() => {
this.message = "Updated message!";
})
}
}
}
// 子组件接收数据
@Component
struct ChildComponent {
@Prop msg: string; // 同步接收父组件数据
build() {
Text(this.msg)
.fontSize(20)
}
}
关键注意事项:
- 权限配置:跨应用通信需在
module.json5 中配置 abilities 的 skills 和 permissions。
- 事件管理:使用
Emitter 时需在组件销毁时取消订阅,避免内存泄漏。
- 数据类型:通过
Want 传递的数据需为可序列化类型(如字符串、数字)。
根据具体场景选择合适方案:跨应用用 Ability 通信,应用内组件用事件总线或数据绑定。