鸿蒙公共事件【坚果派】

公共事件

OpenHarmony 提供了许多系统事件,比如屏幕息屏亮屏事件、USB插拔事件以及APP的安装卸载等,由于这些事件是系统发出的,如果需要监听这些系统事件,比如设备电量低需要给用户提示充电等场景该怎么办喃?ArkUI开发框架给我们提供了 @ohos.commonEventManager 模块,它不仅可以订阅系统事件,而且还可以订阅和发布自定义事件,本节笔者简单介绍一下该库相关 API 的使用。

commonEventManager定义介绍

declare namespace commonEventManager {
    
    
  function publish(event: string, callback: AsyncCallback<void>): void;
  function publish(event: string, options: CommonEventPublishData, callback: AsyncCallback<void>): void;
  function publishAsUser(event: string, userId: number, callback: AsyncCallback<void>): void;
  function publishAsUser(event: string, userId: number, options: CommonEventPublishData, callback: AsyncCallback<void>): void;
  function createSubscriber(subscribeInfo: CommonEventSubscribeInfo, callback: AsyncCallback<CommonEventSubscriber>): void;
  function createSubscriber(subscribeInfo: CommonEventSubscribeInfo): Promise<CommonEventSubscriber>;
  function subscribe(subscriber: CommonEventSubscriber, callback: AsyncCallback<CommonEventData>): void;
  function unsubscribe(subscriber: CommonEventSubscriber, callback?: AsyncCallback<void>): void;
}
  • publish:发送公共事件,event 表示事件名称。
  • publishAsUser:发送指定用户的公共事件。
  • createSubscriber:创建事件的订阅者。
  • subscribe:订阅事件,可以是公共事件,也可以是自定义事件。
  • unsubscribe:取消订阅事件,一旦取消,后续对的事件将不再接收。

@ohos.commonEventManager 模块提供的 API 使用很简单,首先创建接收事件的订阅者,然后开始订阅事件,最后取消订阅。发布事件直接调用 publish() 方法发布事件即可,如果事件匹配到订阅者订阅的事件类型,就会回调给订阅者,

完整源码

import commonEvent from '@ohos.commonEventManager'; // 引入事件包

@Entry
@Component
struct Index {
    
    
  @State text: string = "";
  @State publish: string = "";
  private subscriber = null;

  private createSubscriber() {
    
    
    if (this.subscriber) {
    
    
      this.text = "subscriber already created";
    } else {
    
    
      commonEvent.createSubscriber({
    
     // 创建订阅者
        events: ["testEvent"]                   // 指定订阅的事件名称
      }, (err, subscriber) => {
    
     // 创建结果的回调
        if (err) {
    
    
          this.text = "create subscriber failure"
        } else {
    
    
          this.subscriber = subscriber; // 创建订阅成功
          this.text = "create subscriber success";
        }
      })
    }
  }

  private subscribe() {
    
    
    if (this.subscriber) {
    
    
      // 根据创建的subscriber开始订阅事件
      commonEvent.subscribe(this.subscriber, (err, data) => {
    
    
        if (err) {
    
    
          // 异常处理
          this.text = "subscribe event failure: " + err;
        } else {
    
    
          // 接收到事件
          this.text = "subscribe event success: " + JSON.stringify(data.event) + ", " + JSON.stringify(data);
        }
      })
    } else {
    
    
      this.text = "please create subscriber";
    }
  }

  private unsubscribe() {
    
    
    if (this.subscriber) {
    
    
      commonEvent.unsubscribe(this.subscriber, (err) => {
    
     // 取消订阅事件
        if (err) {
    
    
          this.text = "unsubscribe event failure: " + err;
        } else {
    
    
          this.subscriber = null;
          this.text = "unsubscribe event success: ";
        }
      })
    } else {
    
    
      this.text = "already subscribed";
    }
  }

  private publishEvent() {
    
    
    commonEvent.publish("testEvent", (err) => {
    
     // 发布事件,事件名称为testEvent
      if (err) {
    
     // 结果回调
        this.publish = "publish event error: " + err.code + ", " + err.message + ", " + err.name + ", " + err.stack;
      } else {
    
    
        this.publish = "publish event success";
      }
    })
  }

  private publishEventWithData() {
    
    
    commonEvent.publish("testEvent", {
    
     // 发布事件,事件名称为testEvent
      code: 10086, // 事件携带的参数
      data: "publish with data",
      parameters: {
    
    
        id: 1,
        content: "坚果"
      }
      // 事件携带的参数
    }, (err) => {
    
     // 结果回调
      if (err) {
    
    
        this.publish = "publish event error: " + err.code + ", " + err.message + ", " + err.name + ", " + err.stack;
      } else {
    
    
        this.publish = "publish event with data success";
      }
    })
  }

  build() {
    
    
    Column({
     
      space: 10 }) {
    
    
      Button("创建订阅者")
        .size({
    
     width: 260, height: 50 })
        .onClick(() => {
    
    
          this.createSubscriber();
        })
      Button("订阅公共事件")
        .size({
    
     width: 260, height: 50 })
        .onClick(() => {
    
    
          this.subscribe();
        })

      Button("取消订阅")
        .size({
    
     width: 260, height: 50 })
        .onClick(() => {
    
    
          this.unsubscribe();
        })

      Text(this.text)
        .size({
    
     width: 260, height: 260 })
        .fontSize(22)
        .backgroundColor("#dbdbdb")

      Divider()
        .size({
    
     width: 260, height: 5 })

      Button("发布公共事件")
        .size({
    
     width: 260, height: 50 })
        .onClick(() => {
    
    
          this.publishEvent();
        })

      Button("发布公共事件指定公共信息")
        .size({
    
     width: 260, height: 50 })
        .onClick(() => {
    
    
          this.publishEventWithData();
        })

      Text(this.publish)
        .size({
    
     width: 260, height: 150 })
        .fontSize(22)
        .backgroundColor("#dbdbdb")

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

完毕

猜你喜欢

转载自blog.csdn.net/qq_39132095/article/details/132796714
今日推荐