• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# @ohos.commonEventManager (Common Event)
2
3The **CommonEventManager** module provides common event capabilities, including the capabilities to publish, subscribe to, and unsubscribe from common events.
4
5> **NOTE**
6>
7> 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.
8
9## Modules to Import
10
11```ts
12import { commonEventManager } from '@kit.BasicServicesKit';
13```
14
15## Support
16
17System 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](./common_event/commonEventManager-definitions.md).
18
19## commonEventManager.publish
20
21publish(event: string, callback: AsyncCallback\<void>): void
22
23Publishes a common event. This API uses an asynchronous callback to return the result.
24
25**Atomic service API**: This API can be used in atomic services since API version 11.
26
27**System capability**: SystemCapability.Notification.CommonEvent
28
29**Parameters**
30
31| Name    | Type                | Mandatory| Description                  |
32| -------- | -------------------- | ---- | ---------------------- |
33| event    | string               | Yes  | Name of the common event to publish. For details, see [System Common Events](./common_event/commonEventManager-definitions.md).|
34| callback | AsyncCallback\<void> | Yes  | Callback used to return the result. If the operation is successful, **err** is **undefined**; otherwise, **err** is an error object.|
35
36**Error codes**
37
38For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Event Error Codes](./errorcode-CommonEventService.md).
39
40| ID| Error Message                           |
41| -------- | ----------------------------------- |
42| 1500003  | The common event sending frequency too high. |
43| 1500007  | Failed to send the message to the common event service. |
44| 1500008  | Failed to initialize the common event service. |
45| 1500009  | Failed to obtain system parameters.  |
46
47**Example**
48
49```ts
50import { BusinessError } from '@kit.BasicServicesKit';
51
52// Publish a common event.
53try {
54  commonEventManager.publish('event', (err: BusinessError) => {
55    if (err) {
56      console.error(`Failed to publish common event. Code is ${err.code}, message is ${err.message}`);
57      return;
58    }
59    console.info(`Succeeded in publishing common event.`);
60  });
61} catch (error) {
62  let err: BusinessError = error as BusinessError;
63  console.error(`Failed to publish common event. Code is ${err.code}, message is ${err.message}`);
64}
65```
66
67## commonEventManager.publish
68
69publish(event: string, options: CommonEventPublishData, callback: AsyncCallback\<void>): void
70
71Publishes a common event. This API uses an asynchronous callback to return the result.
72
73**Atomic service API**: This API can be used in atomic services since API version 11.
74
75**System capability**: SystemCapability.Notification.CommonEvent
76
77**Parameters**
78
79| Name    | Type                  | Mandatory| Description                  |
80| -------- | ---------------------- | ---- | ---------------------- |
81| event    | string                 | Yes  | Name of the common event to publish. For details, see [System Common Events](./common_event/commonEventManager-definitions.md). |
82| options  | [CommonEventPublishData](./js-apis-inner-commonEvent-commonEventPublishData.md) | Yes  | Attributes of the common event to publish.|
83| callback | AsyncCallback\<void>   | Yes  | Callback used to return the result. If the operation is successful, **err** is **undefined**; otherwise, **err** is an error object. |
84
85**Error codes**
86
87For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Event Error Codes](./errorcode-CommonEventService.md).
88
89| ID| Error Message                           |
90| -------- | ----------------------------------- |
91| 1500003  | The common event sending frequency too high. |
92| 1500007  | Failed to send the message to the common event service. |
93| 1500008  | Failed to initialize the common event service. |
94| 1500009  | Failed to obtain system parameters.  |
95
96**Example**
97
98```ts
99import { BusinessError } from '@kit.BasicServicesKit';
100
101// Common event information. The following uses an ordered common event as an example.
102let options: commonEventManager.CommonEventPublishData = {
103  code: 0,
104  data: 'initial data',
105  isOrdered: true // The common event is an ordered one.
106}
107
108// Publish a common event.
109try {
110  commonEventManager.publish('event', options, (err: BusinessError) => {
111    if (err) {
112      console.error(`Failed to publish common event. Code is ${err.code}, message is ${err.message}`);
113      return;
114    }
115    console.info(`Succeeded in publishing common event.`);
116  });
117} catch (error) {
118  let err: BusinessError = error as BusinessError;
119  console.error(`Failed to publish common event. Code is ${err.code}, message is ${err.message}`);
120}
121```
122
123## commonEventManager.createSubscriber
124
125createSubscriber(subscribeInfo: CommonEventSubscribeInfo, callback: AsyncCallback\<CommonEventSubscriber>): void
126
127Creates a subscriber. This API uses an asynchronous callback to return the result.
128
129**Atomic service API**: This API can be used in atomic services since API version 11.
130
131**System capability**: SystemCapability.Notification.CommonEvent
132
133**Parameters**
134
135| Name         | Type                                                        | Mandatory| Description                      |
136| ------------- | ------------------------------------------------------------ | ---- | -------------------------- |
137| subscribeInfo | [CommonEventSubscribeInfo](./js-apis-inner-commonEvent-commonEventSubscribeInfo.md)        | Yes  | Subscriber information.            |
138| callback      | AsyncCallback\<[CommonEventSubscriber](./js-apis-inner-commonEvent-commonEventSubscriber.md)> | Yes  | Callback used to return the result. If the operation is successful, **err** is **undefined**; otherwise, **err** is an error object.|
139
140**Error codes**
141
142For details about the error codes, see [Universal Error Codes](../errorcode-universal.md).
143
144| ID| Error Message                           |
145| -------- | ----------------------------------- |
146| 401     | Parameter error. Possible causes:<br>1. Mandatory parameters are left unspecified.<br>2. Incorrect parameter types.<br>3. Parameter verification failed.    |
147
148**Example**
149
150```ts
151import { BusinessError } from '@kit.BasicServicesKit';
152
153// Define a subscriber to save the created subscriber object for subsequent subscription and unsubscription.
154let subscriber: commonEventManager.CommonEventSubscriber;
155// Attributes of a subscriber.
156let subscribeInfo: commonEventManager.CommonEventSubscribeInfo = {
157  events: ['event']
158};
159
160// Create a subscriber.
161try {
162  commonEventManager.createSubscriber(subscribeInfo,
163    (err: BusinessError, commonEventSubscriber: commonEventManager.CommonEventSubscriber) => {
164      if(!err) {
165        console.info(`Succeeded in creating subscriber.`);
166        subscriber = commonEventSubscriber;
167        return;
168      }
169      console.error(`Failed to create subscriber. Code is ${err.code}, message is ${err.message}`);
170    });
171} catch (error) {
172  let err: BusinessError = error as BusinessError;
173  console.error(`Failed to create subscriber. Code is ${err.code}, message is ${err.message}`);
174}
175```
176
177## commonEventManager.createSubscriber
178
179createSubscriber(subscribeInfo: CommonEventSubscribeInfo): Promise\<CommonEventSubscriber>
180
181Creates a subscriber. This API uses a promise to return the result.
182
183**Atomic service API**: This API can be used in atomic services since API version 11.
184
185**System capability**: SystemCapability.Notification.CommonEvent
186
187**Parameters**
188
189| Name         | Type                                                 | Mandatory| Description          |
190| ------------- | ----------------------------------------------------- | ---- | -------------- |
191| subscribeInfo | [CommonEventSubscribeInfo](./js-apis-inner-commonEvent-commonEventSubscribeInfo.md) | Yes  | Subscriber information.|
192
193**Return value**
194| Type                                                     | Description            |
195| --------------------------------------------------------- | ---------------- |
196| Promise\<[CommonEventSubscriber](./js-apis-inner-commonEvent-commonEventSubscriber.md)> | Promise used to return the result.|
197
198**Error codes**
199
200For details about the error codes, see [Universal Error Codes](../errorcode-universal.md).
201
202| ID| Error Message                           |
203| -------- | ----------------------------------- |
204| 401     | Parameter error. Possible causes:<br>1. Mandatory parameters are left unspecified.<br>2. Incorrect parameter types.<br>3. Parameter verification failed.      |
205
206**Example**
207
208```ts
209import { BusinessError } from '@kit.BasicServicesKit';
210
211// Define a subscriber to save the created subscriber object for subsequent subscription and unsubscription.
212let subscriber: commonEventManager.CommonEventSubscriber;
213// Attributes of a subscriber.
214let subscribeInfo: commonEventManager.CommonEventSubscribeInfo = {
215  events: ['event']
216};
217// Create a subscriber.
218commonEventManager.createSubscriber(subscribeInfo).then((commonEventSubscriber: commonEventManager.CommonEventSubscriber) => {
219  console.info(`Succeeded in creating subscriber.`);
220  subscriber = commonEventSubscriber;
221}).catch((err: BusinessError) => {
222  console.error(`Failed to create subscriber. Code is ${err.code}, message is ${err.message}`);
223});
224```
225
226## commonEventManager.createSubscriberSync<sup>10+</sup>
227
228createSubscriberSync(subscribeInfo: CommonEventSubscribeInfo): CommonEventSubscriber
229
230Creates a subscriber. The API returns the result synchronously.
231
232**Atomic service API**: This API can be used in atomic services since API version 11.
233
234**System capability**: SystemCapability.Notification.CommonEvent
235
236**Parameters**
237
238| Name         | Type                                                 | Mandatory| Description          |
239| ------------- | ----------------------------------------------------- | ---- | -------------- |
240| subscribeInfo | [CommonEventSubscribeInfo](./js-apis-inner-commonEvent-commonEventSubscribeInfo.md) | Yes  | Subscriber information.|
241
242**Return value**
243| Type                                                     | Description            |
244| --------------------------------------------------------- | ---------------- |
245| [CommonEventSubscriber](./js-apis-inner-commonEvent-commonEventSubscriber.md) | Promise used to return the subscriber object.|
246
247**Error codes**
248
249For details about the error codes, see [Universal Error Codes](../errorcode-universal.md).
250
251| ID| Error Message                           |
252| -------- | ----------------------------------- |
253| 401     | Parameter error. Possible causes:<br>1. Mandatory parameters are left unspecified.<br>2. Incorrect parameter types.<br>3. Parameter verification failed.      |
254
255**Example**
256
257```ts
258import { BusinessError } from '@kit.BasicServicesKit';
259
260// Define a subscriber to save the created subscriber object for subsequent subscription and unsubscription.
261let subscriber: commonEventManager.CommonEventSubscriber;
262// Attributes of a subscriber.
263let subscribeInfo: commonEventManager.CommonEventSubscribeInfo = {
264  events: ['event']
265};
266// Create a subscriber.
267try {
268  subscriber = commonEventManager.createSubscriberSync(subscribeInfo);
269} catch (error) {
270  let err: BusinessError = error as BusinessError;
271  console.error(`Failed to create subscriber. Code is ${err.code}, message is ${err.message}`);
272}
273```
274
275## commonEventManager.subscribe
276
277subscribe(subscriber: CommonEventSubscriber, callback: AsyncCallback\<CommonEventData>): void
278
279Subscribes to a common event. This API uses an asynchronous callback to return the result.
280
281**Atomic service API**: This API can be used in atomic services since API version 11.
282
283**System capability**: SystemCapability.Notification.CommonEvent
284
285**Parameters**
286
287| Name      | Type                                               | Mandatory| Description                            |
288| ---------- | ---------------------------------------------------- | ---- | -------------------------------- |
289| subscriber | [CommonEventSubscriber](./js-apis-inner-commonEvent-commonEventSubscriber.md)     | Yes  | Subscriber object.                |
290| callback   | AsyncCallback\<[CommonEventData](./js-apis-inner-commonEvent-commonEventData.md)> | Yes  | Callback triggered if the operation is successful; otherwise, **err** is an error object.|
291
292**Error codes**
293
294For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Event Error Codes](./errorcode-CommonEventService.md).
295
296| ID| Error Message                           |
297| -------- | ----------------------------------- |
298| 801  | capability not supported.               |
299| 1500007  | Failed to send the message to the common event service. |
300| 1500008  | Failed to initialize the common event service. |
301| 1500010  | The count of subscriber exceed system specification. |
302
303**Example**
304
305```ts
306import { BusinessError } from '@kit.BasicServicesKit';
307
308// Define a subscriber to save the created subscriber object for subsequent subscription and unsubscription.
309let subscriber: commonEventManager.CommonEventSubscriber;
310// Attributes of a subscriber.
311let subscribeInfo: commonEventManager.CommonEventSubscribeInfo = {
312  events: ['event']
313};
314
315// Create a subscriber.
316try {
317  commonEventManager.createSubscriber(subscribeInfo,
318    (err: BusinessError, commonEventSubscriber: commonEventManager.CommonEventSubscriber) => {
319      if(!err) {
320        console.info(`Succeeded in creating subscriber.`);
321        subscriber = commonEventSubscriber;
322        // Subscribe to a common event.
323        try {
324          commonEventManager.subscribe(subscriber, (err: BusinessError, data: commonEventManager.CommonEventData) => {
325            if (err) {
326              console.error(`Failed to subscribe. Code is ${err.code}, message is ${err.message}`);
327              return;
328            }
329            console.info(`Succeeded in subscribing, data is ${JSON.stringify(data)}`);
330          });
331        } catch (error) {
332          let err: BusinessError = error as BusinessError;
333          console.error(`Failed to subscribe. Code is ${err.code}, message is ${err.message}`);
334        }
335        return;
336      }
337      console.error(`Failed to create subscriber. Code is ${err.code}, message is ${err.message}`);
338    });
339} catch (error) {
340  let err: BusinessError = error as BusinessError;
341  console.error(`Failed to create subscriber. Code is ${err.code}, message is ${err.message}`);
342}
343```
344
345## commonEventManager.unsubscribe
346
347unsubscribe(subscriber: CommonEventSubscriber, callback?: AsyncCallback\<void>): void
348
349Unsubscribes from a common event. This API uses an asynchronous callback to return the result.
350
351**Atomic service API**: This API can be used in atomic services since API version 11.
352
353**System capability**: SystemCapability.Notification.CommonEvent
354
355**Parameters**
356
357| Name      | Type                                            | Mandatory| Description                    |
358| ---------- | ----------------------------------------------- | ---- | ------------------------ |
359| subscriber | [CommonEventSubscriber](./js-apis-inner-commonEvent-commonEventSubscriber.md) | Yes  | Subscriber object.        |
360| callback   | AsyncCallback\<void>                            | No  | Callback to unregister. If the operation is successful, **err** is **undefined**; otherwise, **err** is an error object.|
361
362**Error codes**
363
364For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Event Error Codes](./errorcode-CommonEventService.md).
365
366| ID| Error Message                           |
367| -------- | ----------------------------------- |
368| 401     | Parameter error. Possible causes:<br>1. Mandatory parameters are left unspecified.<br>2. Incorrect parameter types.<br>3. Parameter verification failed.      |
369| 801  | capability not supported.               |
370| 1500007  | Failed to send the message to the common event service. |
371| 1500008  | Failed to initialize the common event service. |
372
373**Example**
374
375```ts
376import { BusinessError } from '@kit.BasicServicesKit';
377
378// Define a subscriber to save the created subscriber object for subsequent subscription and unsubscription.
379let subscriber: commonEventManager.CommonEventSubscriber | undefined;
380// Attributes of a subscriber.
381let subscribeInfo: commonEventManager.CommonEventSubscribeInfo = {
382  events: ['event']
383};
384
385// Create a subscriber.
386try {
387  commonEventManager.createSubscriber(subscribeInfo,
388    (err: BusinessError, commonEventSubscriber: commonEventManager.CommonEventSubscriber) => {
389      if(!err) {
390        console.info(`Succeeded in creating subscriber.`);
391        subscriber = commonEventSubscriber;
392        // Subscribe to a common event.
393        try {
394          commonEventManager.subscribe(subscriber, (err: BusinessError, data: commonEventManager.CommonEventData) => {
395            if (err) {
396              console.error(`Failed to subscribe. Code is ${err.code}, message is ${err.message}`);
397              return;
398            }
399            console.info(`Succeeded in subscribing, data is ${JSON.stringify(data)}`);
400          });
401        } catch (error) {
402          let err: BusinessError = error as BusinessError;
403          console.error(`Failed to subscribe. Code is ${err.code}, message is ${err.message}`);
404        }
405        return;
406      }
407      console.error(`Failed to create subscriber. Code is ${err.code}, message is ${err.message}`);
408    });
409} catch (error) {
410  let err: BusinessError = error as BusinessError;
411  console.error(`Failed to create subscriber. Code is ${err.code}, message is ${err.message}`);
412}
413
414// Unsubscribe from the common event.
415// Wait until execution of the asynchronous API subscribe is completed. Add setTimeout when necessary.
416setTimeout(() => {
417  try {
418    commonEventManager.unsubscribe(subscriber, (err: BusinessError) => {
419      if (err) {
420        console.error(`Failed to unsubscribe. Code is ${err.code}, message is ${err.message}`);
421        return;
422      }
423      // If the subscriber is no longer used, set it to undefined to avoid memory leakage.
424      subscriber = undefined;
425      console.info(`Succeeded in unsubscribing.`);
426    });
427  } catch (error) {
428    let err: BusinessError = error as BusinessError;
429    console.error(`Failed to unsubscribe. Code is ${err.code}, message is ${err.message}`);
430  }
431}, 500);
432```
433
434## commonEventManager.subscribeToEvent<sup>20+</sup>
435
436subscribeToEvent(subscriber: CommonEventSubscriber, callback: Callback\<CommonEventData>): Promise\<void>
437
438Subscribes to common events. This API uses a promise to return the result, indicating subscription success or failure. This API uses a promise to return the result.
439
440**Atomic service API**: This API can be used in atomic services since API version 20.
441
442**System capability**: SystemCapability.Notification.CommonEvent
443
444**Parameters**
445
446| Name      | Type                                               | Mandatory| Description                            |
447| ---------- | ---------------------------------------------------- | ---- | -------------------------------- |
448| subscriber | [CommonEventSubscriber](./js-apis-inner-commonEvent-commonEventSubscriber.md)     | Yes  | Subscriber object.                |
449| callback   | Callback\<[CommonEventData](./js-apis-inner-commonEvent-commonEventData.md)> | Yes  | Callback to be invoked when a common event is subscribed to.|
450
451**Return value**
452| Type                                                     | Description            |
453| --------------------------------------------------------- | ---------------- |
454| Promise\<void>   | Promise that returns no value.|
455
456**Error codes**
457
458For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Event Error Codes](./errorcode-CommonEventService.md).
459
460| ID| Error Message                           |
461| -------- | ----------------------------------- |
462| 801  | Capability not supported.               |
463| 1500007  | Failed to send the message to the common event service. |
464| 1500008  | Failed to initialize the common event service. |
465| 1500010  | The count of subscriber exceed system specification. |
466
467**Example**
468
469```ts
470import { BusinessError } from '@kit.BasicServicesKit';
471
472// Define a subscriber to save the created subscriber object for subsequent subscription and unsubscription.
473let subscriber: commonEventManager.CommonEventSubscriber;
474// Attributes of a subscriber.
475let subscribeInfo: commonEventManager.CommonEventSubscribeInfo = {
476  events: ["event"]
477};
478
479// Create a subscriber.
480try {
481  commonEventManager.createSubscriber(subscribeInfo,
482    (err: BusinessError, commonEventSubscriber: commonEventManager.CommonEventSubscriber) => {
483      if (err) {
484        console.error(`Failed to create subscriber. Code is ${err.code}, message is ${err.message}`);
485      } else {
486        console.info(`Succeeded in creating subscriber.`);
487        subscriber = commonEventSubscriber;
488        // Subscribe to a common event.
489        try {
490          commonEventManager.subscribeToEvent(subscriber, (data: commonEventManager.CommonEventData) => {
491            console.info(`Succeeded to receive common event, data is ` + JSON.stringify(data));
492          }).then(() => {
493            console.info(`Succeeded to subscribe.`);
494          }).catch((err: BusinessError) => {
495            console.error(`Failed to subscribe. Code is ${err.code}, message is ${err.message}`);
496          });
497        } catch (error) {
498          let err: BusinessError = error as BusinessError;
499          console.error(`Failed to subscribe. Code is ${err.code}, message is ${err.message}`);
500        }
501      }
502    });
503} catch (error) {
504  let err: BusinessError = error as BusinessError;
505  console.error(`Failed to create subscriber. Code is ${err.code}, message is ${err.message}`);
506}
507```
508
509## CommonEventData<sup>10+</sup>
510
511type CommonEventData = _CommonEventData
512
513Describes the data of a common event.
514
515**Atomic service API**: This API can be used in atomic services since API version 11.
516
517**System capability**: SystemCapability.Notification.CommonEvent
518
519| Type| Description|
520| --- | --- |
521| [_CommonEventData](js-apis-inner-commonEvent-commonEventData.md) | Data of a common event.|
522
523## CommonEventSubscriber<sup>10+</sup>
524
525type CommonEventSubscriber = _CommonEventSubscriber
526
527Describes the subscriber of a common event.
528
529**Atomic service API**: This API can be used in atomic services since API version 11.
530
531**System capability**: SystemCapability.Notification.CommonEvent
532
533| Type| Description|
534| --- | --- |
535| [_CommonEventSubscriber](js-apis-inner-commonEvent-commonEventSubscriber.md) | Subscriber of a common event.|
536
537## CommonEventSubscribeInfo<sup>10+</sup>
538
539type CommonEventSubscribeInfo = _CommonEventSubscribeInfo
540
541Describes the information about a subscriber.
542
543**Atomic service API**: This API can be used in atomic services since API version 11.
544
545**System capability**: SystemCapability.Notification.CommonEvent
546
547| Type| Description|
548| --- | --- |
549| [_CommonEventSubscribeInfo](js-apis-inner-commonEvent-commonEventSubscribeInfo.md) | Information about a subscriber.|
550
551## CommonEventPublishData<sup>10+</sup>
552
553type CommonEventPublishData = _CommonEventPublishData
554
555Describes the content and attributes of a common event.
556
557**Atomic service API**: This API can be used in atomic services since API version 11.
558
559**System capability**: SystemCapability.Notification.CommonEvent
560
561| Type| Description|
562| --- | --- |
563| [_CommonEventPublishData](js-apis-inner-commonEvent-commonEventPublishData.md) | Content and attributes of a common event.|
564