HarmonyOS应用开发实战:猫猫大作战-EventHub 的使用

发布时间:2026/7/28 4:37:04
HarmonyOS应用开发实战:猫猫大作战-EventHub 的使用 前言在 HarmonyOS 中EventHub是 UIAbility 与页面之间的事件通信机制。当 Ability 需要通知页面某些事件发生时如切换到后台、配置文件变更EventHub 提供了一种松耦合的通信方式。本文以「猫猫大作战」的 Ability 通知页面暂停/恢复为锚点讲解 EventHub 的使用。提示本系列不讲 ArkTS 基础语法与环境搭建假设你已跟完第 1–107 篇。本篇是阶段三第 108 篇。一、EventHub 基本用法1.1 获取 EventHub// EntryAbility.ets export default class EntryAbility extends UIAbility { onForeground() { // 通过 EventHub 发送事件 this.context.eventHub.emit(foreground); } onBackground() { this.context.eventHub.emit(background); } }1.2 页面接收事件// Index.ets — 通过 UIAbilityContext 获取 EventHub import { common } from kit.AbilityKit; aboutToAppear() { const context getContext() as common.UIAbilityContext; context.eventHub.on(background, () { this.pauseGame(); }); context.eventHub.on(foreground, () { this.resumeGame(); }); } aboutToDisappear() { const context getContext() as common.UIAbilityContext; context.eventHub.off(background); context.eventHub.off(foreground); }二、事件参数传递// Ability 发送带参数的事件 this.context.eventHub.emit(scoreUpdate, 88888); // 页面接收参数 context.eventHub.on(scoreUpdate, (score: number) { this.highScore score; });三、常见踩坑// 忘记在 aboutToDisappear 中注销事件 aboutToDisappear() { // 缺少 context.eventHub.off(background); // → 内存泄漏 }四、总结EventHub 实现 Ability 与页面之间的松耦合通信适合前后台切换、配置文件变更等场景。核心要点context.eventHub.emit(event, ...args)发送事件context.eventHub.on(event, callback)接收事件context.eventHub.off(event)必须注销否则内存泄漏下一篇预告第 109 篇将深入 Want 启动——通过 startAbility 启动其他页面或 Ability。如果这篇文章对你有帮助欢迎点赞、收藏⭐、关注你的支持是我持续创作的动力相关资源EventHub API 参考UIAbilityContext 文档开源鸿蒙跨平台社区第 107 篇Extend第 109 篇Want 启动