harmony 鸿蒙Publishing Common Events

  • 2023-02-03
  • 浏览 (647)

Publishing Common Events

When to Use

You can use publish() to publish a custom common event, which can carry data for subscribers to parse and process.

NOTE

Subscribers can receive sticky common events that have been sent. However, they must subscribe to common events of other types before receiving them. For details about subscription, see Subscribing to Common Events.

Available APIs

For details about the APIs, see API Reference.

API Description
publish(event: string, callback: AsyncCallback) Publishes a common event.
publish(event: string, options: CommonEventPublishData, callback: AsyncCallback) Publishes a common event with given attributes.

Publishing a Common Event That Does Not Carry Information

Common events that do not carry information can be published only as unordered common events.

  1. Import the commonEventManager module.
   import commonEventManager from '@ohos.commonEventManager';
   import Base from '@ohos.base';
  1. Pass in the common event name and callback, and publish the event.
   // Publish a common event.
   commonEventManager.publish("usual.event.SCREEN_OFF", (err: Base.BusinessError) => {
       if (err) {
           console.error(`[CommonEvent] PublishCallBack err=${JSON.stringify(err)}`);
       } else {
           console.info(`[CommonEvent] Publish success`);
       }
   });

Publishing a Common Event That Carries Information

Common events that carry information can be published as unordered, ordered, and sticky common events, which are specified by the isOrdered and isSticky fields of CommonEventPublishData.

  1. Import the commonEventManager module.
   import commonEventManager from '@ohos.commonEventManager';
   import Base from '@ohos.base';
  1. Pass in the common event name and callback, and publish the event.
   // Attributes of a common event.
   let options: commonEventManager.CommonEventPublishData = {
       code: 1, // Result code of the common event.
       data: "initial data", // Result data of the common event.
   }
  1. Pass in the common event name, attributes of the common event, and callback, and publish the event.
   // Publish a common event.
   commonEventManager.publish("usual.event.SCREEN_OFF", options, (err: Base.BusinessError) => {
       if (err) {
           console.error('[CommonEvent] PublishCallBack err=' + JSON.stringify(err));
       } else {
           console.info('[CommonEvent] Publish success')
       }
   });

你可能感兴趣的鸿蒙文章

harmony 鸿蒙Application Models

harmony 鸿蒙Using Explicit Want to Start an Application Component

harmony 鸿蒙Using Implicit Want to Open a Website

harmony 鸿蒙AbilityStage Component Container

harmony 鸿蒙Accessing a DataAbility

harmony 鸿蒙Accessing a DataShareExtensionAbility from the FA Model

harmony 鸿蒙AccessibilityExtensionAbility

harmony 鸿蒙Common action and entities Values

harmony 鸿蒙API Switching Overview

harmony 鸿蒙Switching of app and deviceConfig

0  赞