如何通过自定义公共事件实现进程间的通信?

如何通过自定义公共事件实现进程间的通信?

HarmonyOS
2024-07-21 12:24:41
浏览
收藏 0
回答 1
回答 1
按赞同
/
按时间
OwenOO
subscriber: commonEventManager.CommonEventSubscriber | null = null;
subscribeInfo: commonEventManager.CommonEventSubscribeInfo = {
  events: ["myEvent"]//自己定义的事件名称
};

aboutToAppear(): void {
  // 创建订阅者回调
  commonEventManager.createSubscriber(this.subscribeInfo,
    (err: Base.BusinessError, data: commonEventManager.CommonEventSubscriber) => {
      if (err) {
        return;
      }
      this.subscriber = data;
      this.scribeSuccess = true
      if (this.subscriber !== null) {
        commonEventManager.subscribe(this.subscriber,
          (err: Base.BusinessError, data: commonEventManager.CommonEventData) => {
            if (err) {
              return;
            }
            console.info("==============success:" + JSON.stringify(data))
          })
      }
    })
}

build() {
  Column() {
    Button("发布事件").onClick(() => {
      let options: commonEventManager.CommonEventPublishData = {
        code: 1, // 公共事件的初始代码
        data: '我是携带的数据', // 公共事件的初始数据
        parameters:[{"name":"zhangsan"}]
      };
      commonEventManager.publish('myEvent', options, (err: Base.BusinessError) => {
        if (err) {
          console.info(`PublishCallBack err = ${JSON.stringify(err)}`);
        } else {
          console.info(`Publish success`);
        }
      });
    })
  }.width("100%")
  .justifyContent(FlexAlign.Center)
  .height("100%")
}

打印日志: ==============success:{"event":"myEvent","bundleName":"","code":1,"data":"我是携带的数据","parameters":{"0":{"name":"zhangsan"},"length":1,"moduleName":""}}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42.
  • 43.
  • 44.
  • 45.
  • 46.
  • 47.
  • 48.
分享
微博
QQ
微信
回复
2024-07-21 18:44:30
相关问题
公共事件实现进程通信
1639浏览 • 1回复 待解决
公共事件有哪些简单使用
1764浏览 • 1回复 待解决
用户订阅系统公共事件
1983浏览 • 1回复 待解决
如何公共事件发布给其他设备
5030浏览 • 1回复 待解决
公共事件生命周期是怎样
2353浏览 • 1回复 待解决
如何实现H5自定义事件
3432浏览 • 1回复 待解决
HarmonyOS 如何实现组件通信
1440浏览 • 1回复 待解决