Subscribing to Common Events in Dynamic Mode

When to Use

In dynamic subscription mode, an application, when it is running, subscribes to a common event and then receives the event once it is published, together with the parameters passed in the event.

For example, if an application expects to be notified of low battery so that it can reduce power consumption accordingly when running, then the application can subscribe to the low-battery event. Upon receiving the event, the application can close some unnecessary tasks to reduce power consumption.

Certain system common events require specific permissions to subscribe to. For details, see System Common Events.

NOTE

The lifecycle of the subscriber object needs to be managed by the application. If the subscriber object is no longer used, unsubscribe from it in dynamic mode to destroy and release it. This way avoids subscription failures of other services and memory leakage when the number of intra-process subscribers exceeds 200.

The callback of common events in dynamic subscription mode is affected by the application status. When the application is in the background, the callback cannot receive common events subscribed dynamically. When the application is switched from the background to the foreground, the callback can receive common events listened for within 30 seconds before the switch.

Common events between the main application and the cloned application are isolated from each other, that is, they cannot receive the common events mutually.

Available APIs

For details about the APIs, see @ohos.commonEventManager (Common Event).

API Description
createSubscriber(subscribeInfo: CommonEventSubscribeInfo, callback: AsyncCallback<CommonEventSubscriber>): void Creates a subscriber. This API uses an asynchronous callback to return the result.
createSubscriber(subscribeInfo: CommonEventSubscribeInfo): Promise<CommonEventSubscriber> Creates a subscriber. This API uses a promise to return the result.
subscribe(subscriber: CommonEventSubscriber, callback: AsyncCallback<CommonEventData>): void Subscribes to common events.

How to Develop

  1. Import the related modules.

    import { BusinessError, commonEventManager } from '@kit.BasicServicesKit';
    import { hilog } from '@kit.PerformanceAnalysisKit';
    
    const TAG: string = 'ProcessModel';
    const DOMAIN_NUMBER: number = 0xFF00;
    
  2. Create a subscribeInfo object. For details about the data types and parameters of the object, see CommonEventSubscribeInfo.

    • Custom common events: defined by applications.

      // Used to save the created subscriber object for subsequent subscription and unsubscription.
      let subscriberCustom: commonEventManager.CommonEventSubscriber | null = null;
      // Subscriber information. Replace the 'event' field with the actual event name.
      let subscribeInfoCustom: commonEventManager.CommonEventSubscribeInfo = {
        events: ['event']  // Subscribe to a custom common event.
      };
      
    • System common events: defined in CES. Currently, only system applications and system services can publish system common events, such as HAP installation, update, and uninstall. For details about the supported system common events, see System Common Events.

      // Used to save the created subscriber object for subsequent subscription and unsubscription.
      let subscriberSystem: commonEventManager.CommonEventSubscriber | null = null;
      // Subscriber information. Use the corresponding common event as required.
      let subscribeInfoSystem: commonEventManager.CommonEventSubscribeInfo = {
        events: [commonEventManager.Support.COMMON_EVENT_SCREEN_OFF]  // Subscribe to the screen-off event.
      };
      
  3. Create a subscriber object and save the returned object for subsequent operations such as subscription, unsubscription, and event callback.

    // Callback for subscriber creation.
    commonEventManager.createSubscriber(subscribeInfoCustom,
      (err: BusinessError, data: commonEventManager.CommonEventSubscriber) => {
        if (err) {
          hilog.error(DOMAIN_NUMBER, TAG,
            `Failed to create subscriber. Code is ${err.code}, message is ${err.message}`);
          return;
        }
        hilog.info(DOMAIN_NUMBER, TAG, 'Succeeded in creating subscriber.');
        subscriberCustom = data;
      })
    
  4. Create a subscription callback, which is triggered when an event is received. The data returned in the subscription callback contains information such as the common event name and data carried by the publisher. For details about the data types and parameters of the common event data, see CommonEventData.

    // Callback for common event subscription.
    if (subscriberCustom !== null) {
      commonEventManager.subscribe(subscriberCustom,
        (err: BusinessError, data: commonEventManager.CommonEventData) => {
          if (err) {
            hilog.error(DOMAIN_NUMBER, TAG,
              `Failed to subscribe common event. Code is ${err.code}, message is ${err.message}`);
            return;
          }
          hilog.info(DOMAIN_NUMBER, TAG, `Succeeded in subscribing, data is ${JSON.stringify(data)}`);
        })
    } else {
      hilog.error(DOMAIN_NUMBER, TAG, `Need create subscriber`);
    }