【HarmonyOS】应用通知广播的使用

【HarmonyOS】应用通知广播的使用

一、通知广播是什么?

应用开发多年的同学,对于时间通知广播是比较熟悉。一般刚接触的同学可能不太清楚,下面简单介绍一下,了解的同学可以跨过,直接看第二节。

通知广播,见名知意,是为了实现将信息,通知给所有人的一种程序方式。那代码中对于信息的形态,通知给所有人的范围就会有定义。

一般而言通知广播会有一个注册key的实例来处理所有广播。每一个广播的发送也是通过这个key发给所有人进行广播。

举一个栗子,我有三家报社有订阅会员机制,报社分别是ABC三家。

对于想看A报社的人来说,只需要去A报社进行订阅即可。这个订阅行为在代码中就是注册key的过程。相应的广播方式,当然也是根据是否有订阅来决定。

其实鸿蒙中的事件广播迭代版本很有意思,在api7的时代,系统应用源码中就就已经有工具类的存在,eventBus的使用很多,例如相机的源码。相机各种状态同步给所有view,基本都是通过广播的形式通知。

虽然鸿蒙中对于子母组件有各种状态同步和监听机制,但是在纯逻辑处理类中就不适用了。所以才会有事件通知广播的场景需求。

随着鸿蒙API的版本迭代,在API10正式将给工具类并入到了系统接口中,方便大家的使用。

曾几何时,两年前我还在开发Openharmony时,都是自己封装的EventBusMgr使用,现在可以直接替换为官网api。基本无感知替换。可见该工具类的受欢迎程度。

二、鸿蒙中如何使用事件通知广播?

EventHub被存放在context上下文中,是单例模式,只有一个。每次可通过上下文获取到该实例。

该实例共有三个函数,分别是emit发送广播,on监听广播,off取消监听广播。

广播发送的包裹可以是任意类型。

三、Demo示例:

DEMO讲解通过注释的方式表明。若有不清楚的点,可关注私信我沟通。

dart 复制代码
import { BusinessError } from '@kit.BasicServicesKit';
import { promptAction } from '@kit.ArkUI';
import { common } from '@kit.AbilityKit';

@Entry
@Component
struct EventHubPage {

  private TAG: string = "EventHubPage";

  private noticeIsDone: boolean = false;

  private TEST_KEY: string = "TEST_KEY";

  private eventHub(){
    let context = getContext() as common.UIAbilityContext;
    return context.eventHub;
  }

  // 这里是收到广播的回调处理
  onTestKey = (noticeIsDone: boolean)=>{
    if(noticeIsDone){
      this.showToast("收到通知,完成!");
    }else{
      this.showToast("收到通知,失败!");
    }
  }

  onClickNotice = ()=>{
    this.noticeIsDone = !this.noticeIsDone;
    // 第二个参数就是需要广播出去的包裹,这里我以boolean类型举例
    this.eventHub().emit(this.TEST_KEY, this.noticeIsDone);
  }

  onClickRegister = ()=>{
    this.eventHub().on(this.TEST_KEY, this.onTestKey);
    this.showToast("注册监听成功!");
  }

  onClickUnRegister = ()=>{
    this.eventHub().off(this.TEST_KEY, this.onTestKey);
    this.showToast("取消注册监听!");
  }

  private showToast(content: string){
    try {
      promptAction.showToast({
        message: content,
        duration: 2000
      });
    } catch (error) {
      let message = (error as BusinessError).message
      let code = (error as BusinessError).code
      console.error(this.TAG, `showToast args error code is ${code}, message is ${message}`);
    };
  }

  /**
   * 统一样式封装
   */
  @Styles ButtonStyle(){
    .width(px2vp(350))
    .height(px2vp(200))
    .margin({ top: px2vp(66) })
  }

  build() {
    Column(){
      Button("发送广播")
        .ButtonStyle()
        .onClick(this.onClickNotice)

      Button("设置注册监听")
        .ButtonStyle()
        .onClick(this.onClickRegister)

      Button("取消注册监听")
        .ButtonStyle()
        .onClick(this.onClickUnRegister)

    }.size({
      width: "100%",
      height: "100%"
    })
  }
}

注意:封装唯一性。因为在不同window中会导致获取的eventhub 不是一个。


dart 复制代码
import { common } from '@kit.AbilityKit';

export class EventHubUtils {

  private static mEventHub: common.EventHub | null = null;

  /**
   * 获取事件通知实例
   * @returns
   */
  public static getEventHub(){
    // 封装唯一性。因为在不同window中会导致获取的eventhub 不是一个。
    if(!EventHubUtils.mEventHub){
      let context = getContext() as common.UIAbilityContext;
      EventHubUtils.mEventHub = context.eventHub;
      console.log("EventHubUtils", "EventIns mEventHub done !");
    }
    return EventHubUtils.mEventHub;
  }
}
相关推荐
●VON11 小时前
双非大学生自学鸿蒙5.0零基础入门到项目实战 -《基础篇》
android·华为·harmonyos·鸿蒙
小虚竹12 小时前
使用仓颉语言实现 nanoid:一个安全的唯一 ID 生成器
运维·服务器·安全·鸿蒙
Damon小智21 小时前
鸿蒙分布式数据服务(DDS)原理与企业同步实战
分布式·华为·harmonyos
猫林老师1 天前
HarmonyOS自动化测试与持续集成实战指南
ci/cd·华为·harmonyos
寂然如故1 天前
拥抱未来:HarmonyOS NEXT 开发新范式深度解析
华为·harmonyos
国霄1 天前
(2)Kotlin/Js For Harmony——如何复用ViewModel
harmonyos
星释1 天前
鸿蒙Flutter三方库适配指南:08.联合插件开发
flutter·华为·harmonyos
爱笑的眼睛111 天前
HarmonyOS WaterFlow瀑布流布局深度解析:从原理到性能优化
华为·harmonyos
星释1 天前
鸿蒙Flutter三方库适配指南:06.插件适配原理
flutter·华为·harmonyos
高沉1 天前
2025华为海思数字IC面经
华为·fpga开发