openharmony 鸿蒙 js-apis-commonEventManager

2025-06-12 浏览 (1)

@ohos.commonEventManager (Common Event)

The CommonEventManager module provides common event capabilities, including the capabilities to publish, subscribe to, and unsubscribe from common events.

NOTE

The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version.

Modules to Import

import { commonEventManager } from '@kit.BasicServicesKit';

Support

System common events refer to events released by system services or system applications. Subscribing to these common events requires specific permissions and values. For details, see System Common Events.

commonEventManager.publish

publish(event: string, callback: AsyncCallback<void>): void

Publishes a common event. This API uses an asynchronous callback to return the result.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.Notification.CommonEvent

Parameters

NameTypeMandatoryDescription
eventstringYesName of the common event to publish. For details, see System Common Events.
callbackAsyncCallback<void>YesCallback used to return the result. If the operation is successful, err is undefined; otherwise, err is an error object.

Error codes

For details about the error codes, see Universal Error Codes and Event Error Codes.

IDError Message
401Parameter error. Possible causes:
1. Mandatory parameters are left unspecified.
2. Incorrect parameter types.
3. Parameter verification failed.
1500007Failed to send the message to the common event service.
1500008Failed to initialize the common event service.
1500009Failed to obtain system parameters.

Example

import { BusinessError } from '@kit.BasicServicesKit';

// Publish a common event.
try {
  commonEventManager.publish('event', (err: BusinessError) => {
    if (err) {
      console.error(`Failed to publish common event. Code is ${err.code}, message is ${err.message}`);
      return;
    }
    console.info(`Succeeded in publishing common event.`);
  });
} catch (error) {
  let err: BusinessError = error as BusinessError;
  console.error(`Failed to publish common event. Code is ${err.code}, message is ${err.message}`);
}

commonEventManager.publish

publish(event: string, options: CommonEventPublishData, callback: AsyncCallback<void>): void

Publishes a common event. This API uses an asynchronous callback to return the result.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.Notification.CommonEvent

Parameters

NameTypeMandatoryDescription
eventstringYesName of the common event to publish. For details, see System Common Events.
optionsCommonEventPublishDataYesAttributes of the common event to publish.
callbacksyncCallback<void>YesCallback used to return the result. If the operation is successful, err is undefined; otherwise, err is an error object.

Error codes

For details about the error codes, see Universal Error Codes and Event Error Codes.

IDError Message
401Parameter error. Possible causes:
1. Mandatory parameters are left unspecified.
2. Incorrect parameter types.
3. Parameter verification failed.
1500007Failed to send the message to the common event service.
1500008Failed to initialize the common event service.
1500009Failed to obtain system parameters.

Example

import { BusinessError } from '@kit.BasicServicesKit';

// Common event information. The following uses an ordered common event as an example.
let options: commonEventManager.CommonEventPublishData = {
  code: 0,
  data: 'initial data',
  isOrdered: true // The common event is an ordered one.
}

// Publish a common event.
try {
  commonEventManager.publish('event', options, (err: BusinessError) => {
    if (err) {
      console.error(`Failed to publish common event. Code is ${err.code}, message is ${err.message}`);
      return;
    }
    console.info(`Succeeded in publishing common event.`);
  });
} catch (error) {
  let err: BusinessError = error as BusinessError;
  console.error(`Failed to publish common event. Code is ${err.code}, message is ${err.message}`);
}

commonEventManager.createSubscriber

createSubscriber(subscribeInfo: CommonEventSubscribeInfo, callback: AsyncCallback<CommonEventSubscriber>): void

Creates a subscriber. This API uses an asynchronous callback to return the result.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.Notification.CommonEvent

Parameters

NameTypeMandatoryDescription
subscribeInfoCommonEventSubscribeInfoYesSubscriber information.
callbackAsyncCallback<CommonEventSubscriber>YesCallback used to return the result. If the operation is successful, err is undefined; otherwise, err is an error object.

Error codes

For details about the error codes, see Universal Error Codes.

IDError Message
401Parameter error. Possible causes:
1. Mandatory parameters are left unspecified.
2. Incorrect parameter types.
3. Parameter verification failed.

Example

import { BusinessError } from '@kit.BasicServicesKit';

// Define a subscriber to save the created subscriber object for subsequent subscription and unsubscription.
let subscriber: commonEventManager.CommonEventSubscriber;
// Attributes of a subscriber.
let subscribeInfo: commonEventManager.CommonEventSubscribeInfo = {
  events: ['event']
};

// Create a subscriber.
try {
  commonEventManager.createSubscriber(subscribeInfo,
    (err: BusinessError, commonEventSubscriber: commonEventManager.CommonEventSubscriber) => {
      if(!err) {
        console.info(`Succeeded in creating subscriber.`);
        subscriber = commonEventSubscriber;
        return;
      }
      console.error(`Failed to create subscriber. Code is ${err.code}, message is ${err.message}`);
    });
} catch (error) {
  let err: BusinessError = error as BusinessError;
  console.error(`Failed to create subscriber. Code is ${err.code}, message is ${err.message}`);
}

commonEventManager.createSubscriber

createSubscriber(subscribeInfo: CommonEventSubscribeInfo): Promise<CommonEventSubscriber>

Creates a subscriber. This API uses a promise to return the result.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.Notification.CommonEvent

Parameters

NameTypeMandatoryDescription
subscribeInfoCommonEventSubscribeInfoYesSubscriber information.

Return value

TypeDescription
Promise<CommonEventSubscriber>Promise used to return the result.

Error codes

For details about the error codes, see Universal Error Codes.

IDError Message
401Parameter error. Possible causes:
1. Mandatory parameters are left unspecified.
2. Incorrect parameter types.
3. Parameter verification failed.

Example

import { BusinessError } from '@kit.BasicServicesKit';

// Define a subscriber to save the created subscriber object for subsequent subscription and unsubscription.
let subscriber: commonEventManager.CommonEventSubscriber;
// Attributes of a subscriber.
let subscribeInfo: commonEventManager.CommonEventSubscribeInfo = {
  events: ['event']
};
// Create a subscriber.
commonEventManager.createSubscriber(subscribeInfo).then((commonEventSubscriber: commonEventManager.CommonEventSubscriber) => {
  console.info(`Succeeded in creating subscriber.`);
  subscriber = commonEventSubscriber;
}).catch((err: BusinessError) => {
  console.error(`Failed to create subscriber. Code is ${err.code}, message is ${err.message}`);
});

commonEventManager.createSubscriberSync10+

createSubscriberSync(subscribeInfo: CommonEventSubscribeInfo): CommonEventSubscriber

Creates a subscriber. The API returns the result synchronously.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.Notification.CommonEvent

Parameters

NameTypeMandatoryDescription
subscribeInfoCommonEventSubscribeInfoYesSubscriber information.

Return value

TypeDescription
CommonEventSubscriberPromise used to return the subscriber object.

Error codes

For details about the error codes, see Universal Error Codes.

IDError Message
401Parameter error. Possible causes:
1. Mandatory parameters are left unspecified.
2. Incorrect parameter types.
3. Parameter verification failed.

Example

import { BusinessError } from '@kit.BasicServicesKit';

// Define a subscriber to save the created subscriber object for subsequent subscription and unsubscription.
let subscriber: commonEventManager.CommonEventSubscriber;
// Attributes of a subscriber.
let subscribeInfo: commonEventManager.CommonEventSubscribeInfo = {
  events: ['event']
};
// Create a subscriber.
try {
  subscriber = commonEventManager.createSubscriberSync(subscribeInfo);
} catch (error) {
  let err: BusinessError = error as BusinessError;
  console.error(`Failed to create subscriber. Code is ${err.code}, message is ${err.message}`);
}

commonEventManager.subscribe

subscribe(subscriber: CommonEventSubscriber, callback: AsyncCallback<CommonEventData>): void

Subscribes to a common event. This API uses an asynchronous callback to return the result.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.Notification.CommonEvent

Parameters

NameTypeMandatoryDescription
subscriberCommonEventSubscriberYesSubscriber object.
callbackAsyncCallback<CommonEventData>YesCallback triggered if the operation is successful; otherwise, err is an error object.

Error codes

For details about the error codes, see Universal Error Codes and Event Error Codes.

IDError Message
401Parameter error. Possible causes:
1. Mandatory parameters are left unspecified.
2. Incorrect parameter types.
3. Parameter verification failed.
801capability not supported.
1500007Failed to send the message to the common event service.
1500008Failed to initialize the common event service.

Example

import { BusinessError } from '@kit.BasicServicesKit';

// Define a subscriber to save the created subscriber object for subsequent subscription and unsubscription.
let subscriber: commonEventManager.CommonEventSubscriber;
// Attributes of a subscriber.
let subscribeInfo: commonEventManager.CommonEventSubscribeInfo = {
  events: ['event']
};

// Create a subscriber.
try {
  commonEventManager.createSubscriber(subscribeInfo,
    (err: BusinessError, commonEventSubscriber: commonEventManager.CommonEventSubscriber) => {
      if(!err) {
        console.info(`Succeeded in creating subscriber.`);
        subscriber = commonEventSubscriber;
        // Subscribe to a common event.
        try {
          commonEventManager.subscribe(subscriber, (err: BusinessError, data: commonEventManager.CommonEventData) => {
            if (err) {
              console.error(`Failed to subscribe. Code is ${err.code}, message is ${err.message}`);
              return;
            }
            console.info(`Succeeded in subscribing, data is ${JSON.stringify(data)}`);
          });
        } catch (error) {
          let err: BusinessError = error as BusinessError;
          console.error(`Failed to subscribe. Code is ${err.code}, message is ${err.message}`);
        }
        return;
      }
      console.error(`Failed to create subscriber. Code is ${err.code}, message is ${err.message}`);
    });
} catch (error) {
  let err: BusinessError = error as BusinessError;
  console.error(`Failed to create subscriber. Code is ${err.code}, message is ${err.message}`);
}

commonEventManager.unsubscribe

unsubscribe(subscriber: CommonEventSubscriber, callback?: AsyncCallback<void>): void

Unsubscribes from a common event. This API uses an asynchronous callback to return the result.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.Notification.CommonEvent

Parameters

NameTypeMandatoryDescription
subscriberCommonEventSubscriberYesSubscriber object.
callbackAsyncCallback<void>NoCallback to unregister. If the operation is successful, err is undefined; otherwise, err is an error object.

Error codes

For details about the error codes, see Universal Error Codes and Event Error Codes.

IDError Message
401Parameter error. Possible causes:
1. Mandatory parameters are left unspecified.
2. Incorrect parameter types.
3. Parameter verification failed.
801capability not supported.
1500007Failed to send the message to the common event service.
1500008Failed to initialize the common event service.

Example

import { BusinessError } from '@kit.BasicServicesKit';

// Define a subscriber to save the created subscriber object for subsequent subscription and unsubscription.
let subscriber: commonEventManager.CommonEventSubscriber|undefined; 
// Attributes of a subscriber.
let subscribeInfo: commonEventManager.CommonEventSubscribeInfo = {
  events: ['event']
};

// Create a subscriber.
try {
  commonEventManager.createSubscriber(subscribeInfo,
    (err: BusinessError, commonEventSubscriber: commonEventManager.CommonEventSubscriber) => {
      if(!err) {
        console.info(`Succeeded in creating subscriber.`);
        subscriber = commonEventSubscriber;
        // Subscribe to a common event.
        try {
          commonEventManager.subscribe(subscriber, (err: BusinessError, data: commonEventManager.CommonEventData) => {
            if (err) {
              console.error(`Failed to subscribe. Code is ${err.code}, message is ${err.message}`);
              return;
            }
            console.info(`Succeeded in subscribing, data is ${JSON.stringify(data)}`);
          });
        } catch (error) {
          let err: BusinessError = error as BusinessError;
          console.error(`Failed to subscribe. Code is ${err.code}, message is ${err.message}`);
        }
        return;
      }
      console.error(`Failed to create subscriber. Code is ${err.code}, message is ${err.message}`);
    });
} catch (error) {
  let err: BusinessError = error as BusinessError;
  console.error(`Failed to create subscriber. Code is ${err.code}, message is ${err.message}`);
}

// Unsubscribe from the common event.
// Wait until execution of the asynchronous API subscribe is completed. Add setTimeout when necessary.
setTimeout(() => {
  try {
    commonEventManager.unsubscribe(subscriber, (err: BusinessError) => {
      if (err) {
        console.error(`Failed to unsubscribe. Code is ${err.code}, message is ${err.message}`);
        return;
      }
      // If the subscriber is no longer used, set it to undefined to avoid memory leakage.
      subscriber = undefined;
      console.info(`Succeeded in unsubscribing.`);
    });
  } catch (error) {
    let err: BusinessError = error as BusinessError;
    console.error(`Failed to unsubscribe. Code is ${err.code}, message is ${err.message}`);
  }
}, 500);

CommonEventData10+

type CommonEventData = _CommonEventData

Describes the data of a common event.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.Notification.CommonEvent

TypeDescription
_CommonEventDataData of a common event.

CommonEventSubscriber10+

type CommonEventSubscriber = _CommonEventSubscriber

Describes the subscriber of a common event.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.Notification.CommonEvent

TypeDescription
_CommonEventSubscriberSubscriber of a common event.

CommonEventSubscribeInfo10+

type CommonEventSubscribeInfo = _CommonEventSubscribeInfo

Describes the information about a subscriber.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.Notification.CommonEvent

TypeDescription
_CommonEventSubscribeInfoInformation about a subscriber.

CommonEventPublishData10+

type CommonEventPublishData = _CommonEventPublishData

Describes the content and attributes of a common event.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.Notification.CommonEvent

TypeDescription
_CommonEventPublishDataContent and attributes of a common event.

你可能感兴趣的鸿蒙文章

harmony 鸿蒙Basic Services Kit

harmony 鸿蒙DeviceInfo

harmony 鸿蒙InitSync

harmony 鸿蒙OH_Print

harmony 鸿蒙OsAccount

harmony 鸿蒙Pasteboard

harmony 鸿蒙Print_Margin

harmony 鸿蒙Print_PageSize

harmony 鸿蒙Print_PrintAttributes

harmony 鸿蒙Print_PrintDocCallback

  • 所属分类: 后端技术
  • 本文标签: 软件 鸿蒙
  • 版权声明: 本文链接 https://seaxiang.com/blog/9tfaQf