• 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 '@ohos.commonEventManager';
13```
14
15## Support
16
17A system common event is an event that is published by a system service or system application and requires specific permissions to subscribe to. To publish or subscribe to this type of event, you must follow the event-specific definitions.
18
19For details about the definitions of all system common events, see [System Common Events](./commonEventManager-definitions.md).
20
21## CommonEventManager.publish
22
23publish(event: string, callback: AsyncCallback\<void>): void
24
25Publishes a common event and executes an asynchronous callback after the event is published.
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.|
34| callback | AsyncCallback\<void> | Yes  | Callback to execute after the event is published.|
35
36**Error codes**
37
38 For details about the error codes, see [Event Error Codes](../errorcodes/errorcode-CommonEventService.md).
39
40| ID| Error Message                           |
41| -------- | ----------------------------------- |
42| 1500004  | not System services.                |
43| 1500007  | error sending message to Common Event Service. |
44| 1500008  | Common Event Service does not complete initialization. |
45| 1500009  | error obtaining system parameters.  |
46
47**Example**
48
49```ts
50import Base from '@ohos.base';
51
52// Callback for common event publication
53function publishCB(err:Base.BusinessError) {
54    if (err) {
55        console.error(`publish failed, code is ${err.code}, message is ${err.message}`);
56    } else {
57        console.info("publish");
58    }
59}
60
61// Publish a common event.
62try {
63    CommonEventManager.publish("event", publishCB);
64} catch (error) {
65    let err:Base.BusinessError = error as Base.BusinessError;
66    console.error(`publish failed, code is ${err.code}, message is ${err.message}`);
67}
68```
69
70## CommonEventManager.publish
71
72publish(event: string, options: CommonEventPublishData, callback: AsyncCallback\<void>): void
73
74Publishes a common event with given attributes. This API uses an asynchronous callback to return the result.
75
76**System capability**: SystemCapability.Notification.CommonEvent
77
78**Parameters**
79
80| Name    | Type                  | Mandatory| Description                  |
81| -------- | ---------------------- | ---- | ---------------------- |
82| event    | string                 | Yes  | Name of the common event to publish. |
83| options  | [CommonEventPublishData](./js-apis-inner-commonEvent-commonEventPublishData.md) | Yes  | Attributes of the common event to publish.|
84| callback | syncCallback\<void>   | Yes  | Callback used to return the result. |
85
86**Error codes**
87
88 For details about the error codes, see [Event Error Codes](../errorcodes/errorcode-CommonEventService.md).
89
90| ID| Error Message                           |
91| -------- | ----------------------------------- |
92| 1500004  | not System services.                |
93| 1500007  | error sending message to Common Event Service. |
94| 1500008  | Common Event Service does not complete initialization. |
95| 1500009  | error obtaining system parameters.  |
96
97**Example**
98
99```ts
100import Base from '@ohos.base';
101
102// Attributes of a common event.
103let options:CommonEventManager.CommonEventPublishData = {
104	code: 0,			 // Result code of the common event.
105	data: "initial data",// Result data of the common event.
106	isOrdered: true	 // The common event is an ordered one.
107}
108
109// Callback for common event publication
110function publishCB(err:Base.BusinessError) {
111	if (err) {
112        console.error(`publish failed, code is ${err.code}, message is ${err.message}`);
113    } else {
114        console.info("publish");
115    }
116}
117
118// Publish a common event.
119try {
120    CommonEventManager.publish("event", options, publishCB);
121} catch (error) {
122    let err:Base.BusinessError = error as Base.BusinessError;
123    console.error(`publish failed, code is ${err.code}, message is ${err.message}`);
124}
125```
126
127## CommonEventManager.publishAsUser<sup>
128
129publishAsUser(event: string, userId: number, callback: AsyncCallback\<void>): void
130
131Publishes a common event to a specific user. This API uses an asynchronous callback to return the result.
132
133**System capability**: SystemCapability.Notification.CommonEvent
134
135**System API**: This is a system API and cannot be called by third-party applications.
136
137**Parameters**
138
139| Name    | Type                | Mandatory| Description                              |
140| -------- | -------------------- | ---- | ---------------------------------- |
141| event    | string               | Yes  | Name of the common event to publish.            |
142| userId   | number               | Yes  | User ID.|
143| callback | AsyncCallback\<void> | Yes  | Callback used to return the result.            |
144
145**Error codes**
146
147 For details about the error codes, see [Event Error Codes](../errorcodes/errorcode-CommonEventService.md).
148
149| ID| Error Message                           |
150| -------- | ----------------------------------- |
151| 1500004  | not System services.                |
152| 1500007  | error sending message to Common Event Service. |
153| 1500008  | Common Event Service does not complete initialization. |
154| 1500009  | error obtaining system parameters.  |
155
156**Example**
157
158```ts
159import Base from '@ohos.base';
160
161// Callback for common event publication
162function publishCB(err:Base.BusinessError) {
163	if (err) {
164        console.error(`publishAsUser failed, code is ${err.code}, message is ${err.message}`);
165    } else {
166        console.info("publishAsUser");
167    }
168}
169
170// Specify the user to whom the common event will be published.
171let userId = 100;
172
173// Publish a common event.
174try {
175    CommonEventManager.publishAsUser("event", userId, publishCB);
176} catch (error) {
177    let err:Base.BusinessError = error as Base.BusinessError;
178    console.error(`publishAsUser failed, code is ${err.code}, message is ${err.message}`);
179}
180```
181
182## CommonEventManager.publishAsUser
183
184publishAsUser(event: string, userId: number, options: CommonEventPublishData, callback: AsyncCallback\<void>): void
185
186Publishes a common event with given attributes to a specific user. This API uses an asynchronous callback to return the result.
187
188**System capability**: SystemCapability.Notification.CommonEvent
189
190**System API**: This is a system API and cannot be called by third-party applications.
191
192**Parameters**
193
194| Name    | Type                  | Mandatory| Description                  |
195| -------- | ---------------------- | ---- | ---------------------- |
196| event    | string                 | Yes  | Name of the common event to publish. |
197| userId   | number | Yes| User ID.|
198| options  | [CommonEventPublishData](./js-apis-inner-commonEvent-commonEventPublishData.md) | Yes  | Attributes of the common event to publish.|
199| callback | AsyncCallback\<void>   | Yes  | Callback used to return the result. |
200
201**Error codes**
202
203 For details about the error codes, see [Event Error Codes](../errorcodes/errorcode-CommonEventService.md).
204
205| ID| Error Message                           |
206| -------- | ----------------------------------- |
207| 1500004  | not System services or System app.                |
208| 1500007  | error sending message to Common Event Service. |
209| 1500008  | Common Event Service does not complete initialization. |
210| 1500009  | error obtaining system parameters.  |
211
212**Example**
213
214
215```ts
216import Base from '@ohos.base';
217
218// Attributes of a common event.
219let options:CommonEventManager.CommonEventPublishData = {
220	code: 0,			 // Result code of the common event.
221	data: "initial data",// Result data of the common event.
222}
223
224// Callback for common event publication.
225function publishCB(err:Base.BusinessError) {
226	if (err) {
227        console.error(`publishAsUser failed, code is ${err.code}, message is ${err.message}`);
228    } else {
229        console.info("publishAsUser");
230    }
231}
232
233// Specify the user to whom the common event will be published.
234let userId = 100;
235
236// Publish a common event.
237try {
238    CommonEventManager.publishAsUser("event", userId, options, publishCB);
239} catch (error) {
240    let err:Base.BusinessError = error as Base.BusinessError;
241    console.error(`publishAsUser failed, code is ${err.code}, message is ${err.message}`);
242}
243```
244
245## CommonEventManager.createSubscriber
246
247createSubscriber(subscribeInfo: CommonEventSubscribeInfo, callback: AsyncCallback\<CommonEventSubscriber>): void
248
249Creates a subscriber. This API uses an asynchronous callback to return the result.
250
251**System capability**: SystemCapability.Notification.CommonEvent
252
253**Parameters**
254
255| Name         | Type                                                        | Mandatory| Description                      |
256| ------------- | ------------------------------------------------------------ | ---- | -------------------------- |
257| subscribeInfo | [CommonEventSubscribeInfo](./js-apis-inner-commonEvent-commonEventSubscribeInfo.md)        | Yes  | Subscriber information.            |
258| callback      | AsyncCallback\<[CommonEventSubscriber](./js-apis-inner-commonEvent-commonEventSubscriber.md)> | Yes  | Callback used to return the result.|
259
260**Example**
261
262```ts
263import Base from '@ohos.base';
264
265let subscriber:CommonEventManager.CommonEventSubscriber; // Used to save the created subscriber object for subsequent subscription and unsubscription.
266
267// Subscriber information.
268let subscribeInfo:CommonEventManager.CommonEventSubscribeInfo = {
269    events: ["event"]
270};
271
272// Callback for subscriber creation.
273function createCB(err:Base.BusinessError, commonEventSubscriber:CommonEventManager.CommonEventSubscriber) {
274    if(!err) {
275        console.info("createSubscriber");
276        subscriber = commonEventSubscriber;
277    } else {
278        console.error(`createSubscriber failed, code is ${err.code}, message is ${err.message}`);
279    }
280}
281
282// Create a subscriber.
283try {
284    CommonEventManager.createSubscriber(subscribeInfo, createCB);
285} catch (error) {
286    let err:Base.BusinessError = error as Base.BusinessError;
287    console.error(`createSubscriber failed, code is ${err.code}, message is ${err.message}`);
288}
289```
290
291## CommonEventManager.createSubscriber
292
293createSubscriber(subscribeInfo: CommonEventSubscribeInfo): Promise\<CommonEventSubscriber>
294
295Creates a subscriber. This API uses a promise to return the result.
296
297**System capability**: SystemCapability.Notification.CommonEvent
298
299**Parameters**
300
301| Name         | Type                                                 | Mandatory| Description          |
302| ------------- | ----------------------------------------------------- | ---- | -------------- |
303| subscribeInfo | [CommonEventSubscribeInfo](./js-apis-inner-commonEvent-commonEventSubscribeInfo.md) | Yes  | Subscriber information.|
304
305**Return value**
306| Type                                                     | Description            |
307| --------------------------------------------------------- | ---------------- |
308| Promise\<[CommonEventSubscriber](./js-apis-inner-commonEvent-commonEventSubscriber.md)> | Promise used to return the subscriber object.|
309
310**Example**
311
312```ts
313import Base from '@ohos.base';
314
315let subscriber:CommonEventManager.CommonEventSubscriber; // Used to save the created subscriber object for subsequent subscription and unsubscription.
316
317// Subscriber information.
318let subscribeInfo:CommonEventManager.CommonEventSubscribeInfo = {
319	events: ["event"]
320};
321
322// Create a subscriber.
323CommonEventManager.createSubscriber(subscribeInfo).then((commonEventSubscriber:CommonEventManager.CommonEventSubscriber) => {
324    console.info("createSubscriber");
325    subscriber = commonEventSubscriber;
326}).catch((err:Base.BusinessError) => {
327    console.error(`createSubscriber failed, code is ${err.code}, message is ${err.message}`);
328});
329
330```
331
332## CommonEventManager.subscribe
333
334subscribe(subscriber: CommonEventSubscriber, callback: AsyncCallback\<CommonEventData>): void
335
336Subscribes to common events. This API uses an asynchronous callback to return the result.
337
338**System capability**: SystemCapability.Notification.CommonEvent
339
340**Parameters**
341
342| Name      | Type                                               | Mandatory| Description                            |
343| ---------- | ---------------------------------------------------- | ---- | -------------------------------- |
344| subscriber | [CommonEventSubscriber](./js-apis-inner-commonEvent-commonEventSubscriber.md)     | Yes  | Subscriber object.                |
345| callback   | AsyncCallback\<[CommonEventData](./js-apis-inner-commonEvent-commonEventData.md)> | Yes  | Callback used to return the result.|
346
347**Error codes**
348
349 For details about the error codes, see [Event Error Codes](../errorcodes/errorcode-CommonEventService.md).
350
351| ID| Error Message                           |
352| -------- | ----------------------------------- |
353| 801  | capability not supported.               |
354| 1500007  | error sending message to Common Event Service. |
355| 1500008  | Common Event Service does not complete initialization. |
356
357**Example**
358
359```ts
360import Base from '@ohos.base';
361
362// Subscriber information.
363let subscriber:CommonEventManager.CommonEventSubscriber; // Used to save the created subscriber object for subsequent subscription and unsubscription.
364
365// Subscriber information.
366let subscribeInfo:CommonEventManager.CommonEventSubscribeInfo = {
367    events: ["event"]
368};
369
370// Callback for common event subscription.
371function SubscribeCB(err:Base.BusinessError, data:CommonEventManager.CommonEventData) {
372    if (err) {
373        console.error(`subscribe failed, code is ${err.code}, message is ${err.message}`);
374    } else {
375        console.info("subscribe ");
376    }
377}
378
379// Callback for subscriber creation.
380function createCB(err:Base.BusinessError, commonEventSubscriber:CommonEventManager.CommonEventSubscriber) {
381    if(!err) {
382        console.info("createSubscriber");
383        subscriber = commonEventSubscriber;
384        // Subscribe to a common event.
385        try {
386            CommonEventManager.subscribe(subscriber, SubscribeCB);
387        } catch (error) {
388            let err:Base.BusinessError = error as Base.BusinessError;
389            console.error(`subscribe failed, code is ${err.code}, message is ${err.message}`);
390        }
391    } else {
392        console.error(`createSubscriber failed, code is ${err.code}, message is ${err.message}`);
393    }
394}
395
396// Create a subscriber.
397try {
398    CommonEventManager.createSubscriber(subscribeInfo, createCB);
399} catch (error) {
400    let err:Base.BusinessError = error as Base.BusinessError;
401    console.error(`createSubscriber failed, code is ${err.code}, message is ${err.message}`);
402}
403```
404
405## CommonEventManager.unsubscribe
406
407unsubscribe(subscriber: CommonEventSubscriber, callback?: AsyncCallback\<void>): void
408
409Unsubscribes from common events. This API uses an asynchronous callback to return the result.
410
411**System capability**: SystemCapability.Notification.CommonEvent
412
413**Parameters**
414
415| Name      | Type                                            | Mandatory| Description                    |
416| ---------- | ----------------------------------------------- | ---- | ------------------------ |
417| subscriber | [CommonEventSubscriber](./js-apis-inner-commonEvent-commonEventSubscriber.md) | Yes  | Subscriber object.        |
418| callback   | AsyncCallback\<void>                            | No  | Callback used to return the result.|
419
420**Error codes**
421
422 For details about the error codes, see [Event Error Codes](../errorcodes/errorcode-CommonEventService.md).
423
424| ID| Error Message                           |
425| -------- | ----------------------------------- |
426| 801  | capability not supported.               |
427| 1500007  | error sending message to Common Event Service. |
428| 1500008  | Common Event Service does not complete initialization. |
429
430**Example**
431
432```ts
433import Base from '@ohos.base';
434
435let subscriber:CommonEventManager.CommonEventSubscriber; // Used to save the created subscriber object for subsequent subscription and unsubscription.
436// Subscriber information.
437let subscribeInfo:CommonEventManager.CommonEventSubscribeInfo = {
438    events: ["event"]
439};
440// Callback for common event subscription.
441function subscribeCB(err:Base.BusinessError, data:CommonEventManager.CommonEventData) {
442    if (err) {
443        console.error(`subscribe failed, code is ${err.code}, message is ${err.message}`);
444    } else {
445        console.info("subscribe");
446    }
447}
448// Callback for subscriber creation.
449function createCB(err:Base.BusinessError, commonEventSubscriber:CommonEventManager.CommonEventSubscriber) {
450    if (err) {
451        console.error(`createSubscriber failed, code is ${err.code}, message is ${err.message}`);
452    } else {
453        console.info("createSubscriber");
454        subscriber = commonEventSubscriber;
455        // Subscribe to a common event.
456        try {
457            CommonEventManager.subscribe(subscriber, subscribeCB);
458        } catch (error) {
459            let err:Base.BusinessError = error as Base.BusinessError;
460            console.error(`subscribe failed, code is ${err.code}, message is ${err.message}`);
461        }
462    }
463}
464// Callback for common event unsubscription.
465function unsubscribeCB(err:Base.BusinessError) {
466    if (err) {
467        console.error(`unsubscribe failed, code is ${err.code}, message is ${err.message}`);
468    } else {
469        console.info("unsubscribe");
470    }
471}
472// Create a subscriber.
473try {
474    CommonEventManager.createSubscriber(subscribeInfo, createCB);
475} catch (error) {
476    let err:Base.BusinessError = error as Base.BusinessError;
477    console.error(`createSubscriber failed, code is ${err.code}, message is ${err.message}`);
478}
479
480// Unsubscribe from the common event.
481try {
482    CommonEventManager.unsubscribe(subscriber, unsubscribeCB);
483} catch (error) {
484    let err:Base.BusinessError = error as Base.BusinessError;
485    console.error(`unsubscribe failed, code is ${err.code}, message is ${err.message}`);
486}
487```
488
489## CommonEventManager.removeStickyCommonEvent<sup>10+</sup>
490
491removeStickyCommonEvent(event: string, callback: AsyncCallback\<void>): void
492
493Removes a sticky common event. This API uses an asynchronous callback to return the result.
494
495**System capability**: SystemCapability.Notification.CommonEvent
496
497**Required permissions**: ohos.permission.COMMONEVENT_STICKY
498
499**System API**: This is a system API and cannot be called by third-party applications.
500
501**Parameters**
502
503| Name  | Type                | Mandatory| Description                            |
504| -------- | -------------------- | ---- | -------------------------------- |
505| event    | string               | Yes  | Sticky common event to remove.      |
506| callback | AsyncCallback\<void> | Yes  | Callback used to return the result.|
507
508**Error codes**
509
510 For details about the error codes, see [Event Error Codes](../errorcodes/errorcode-CommonEventService.md).
511
512| ID| Error Message                           |
513| -------- | ----------------------------------- |
514| 1500004  | not system service.                 |
515| 1500007  | error sending message to Common Event Service.             |
516| 1500008  | Common Event Service does not complete initialization.     |
517
518**Example**
519
520
521```ts
522import Base from '@ohos.base';
523
524CommonEventManager.removeStickyCommonEvent("sticky_event", (err:Base.BusinessError) => {
525    if (err) {
526        console.info(`Remove sticky event AsyncCallback failed, errCode: ${err.code}, errMes: ${err.message}`);
527        return;
528    }
529    console.info(`Remove sticky event AsyncCallback success`);
530});
531```
532
533## CommonEventManager.removeStickyCommonEvent<sup>10+</sup>
534
535removeStickyCommonEvent(event: string): Promise\<void>
536
537Removes a sticky common event. This API uses a promise to return the result.
538
539**System capability**: SystemCapability.Notification.CommonEvent
540
541**Required permissions**: ohos.permission.COMMONEVENT_STICKY
542
543**System API**: This is a system API and cannot be called by third-party applications.
544
545**Parameters**
546
547| Name| Type  | Mandatory| Description                      |
548| ------ | ------ | ---- | -------------------------- |
549| event  | string | Yes  | Sticky common event to remove.|
550
551**Return value**
552
553| Type          | Description                        |
554| -------------- | ---------------------------- |
555| Promise\<void> | Promise used to return the result.|
556
557**Error codes**
558
559 For details about the error codes, see [Event Error Codes](../errorcodes/errorcode-CommonEventService.md).
560
561| ID| Error Message                           |
562| -------- | ----------------------------------- |
563| 1500004  | not system service.                 |
564| 1500007  | error sending message to Common Event Service.             |
565| 1500008  | Common Event Service does not complete initialization.     |
566
567**Example**
568
569
570```ts
571import Base from '@ohos.base';
572
573CommonEventManager.removeStickyCommonEvent("sticky_event").then(() => {
574    console.info(`Remove sticky event AsyncCallback success`);
575}).catch ((err:Base.BusinessError) => {
576    console.info(`Remove sticky event AsyncCallback failed, errCode: ${err.code}, errMes: ${err.message}`);
577});
578```
579
580## CommonEventManager.setStaticSubscriberState<sup>10+</sup>
581
582setStaticSubscriberState(enable: boolean, callback: AsyncCallback\<void>): void;
583
584Enables or disables static subscription for the current application. This API uses an asynchronous callback to return the result.
585
586**System capability**: SystemCapability.Notification.CommonEvent
587
588**System API**: This is a system API and cannot be called by third-party applications.
589
590**Parameters**
591
592| Name| Type  | Mandatory| Description                      |
593| ------ | ------ | ---- | -------------------------- |
594| enable  | boolean | Yes  | Whether static subscription is enabled.<br> **true**: enabled.<br>**false**: disabled.|
595| callback  | AsyncCallback\<void> | Yes  | Callback used to return the result.|
596
597**Error codes**
598
599 For details about the error codes, see [Event Error Codes](../errorcodes/errorcode-CommonEventService.md).
600
601| ID| Error Message                           |
602| -------- | ----------------------------------- |
603| 1500007  | error sending message to Common Event Service.             |
604| 1500008  | Common Event Service does not complete initialization.     |
605
606**Example**
607
608
609```ts
610import Base from '@ohos.base';
611
612CommonEventManager.setStaticSubscriberState(true, (err:Base.BusinessError) => {
613    if (!err) {
614        console.info(`Set static subscriber state callback failed, err is null.`);
615        return;
616    }
617    if (err.code !== undefined && err.code != null) {
618        console.info(`Set static subscriber state callback failed, errCode: ${err.code}, errMes: ${err.message}`);
619        return;
620    }
621    console.info(`Set static subscriber state callback success`);
622});
623```
624
625## CommonEventManager.setStaticSubscriberState<sup>10+</sup>
626
627setStaticSubscriberState(enable: boolean): Promise\<void>;
628
629Enables or disables static subscription for the current application. This API uses a promise to return the result.
630
631**System capability**: SystemCapability.Notification.CommonEvent
632
633**System API**: This is a system API and cannot be called by third-party applications.
634
635**Parameters**
636
637| Name| Type  | Mandatory| Description                      |
638| ------ | ------ | ---- | -------------------------- |
639| enable  | boolean | Yes  | Whether static subscription is enabled.<br> **true**: enabled.<br>**false**: disabled.|
640
641**Return value**
642
643| Type          | Description                        |
644| -------------- | ---------------------------- |
645| Promise\<void> | Promise used to return the result.|
646
647**Error codes**
648
649 For details about the error codes, see [Event Error Codes](../errorcodes/errorcode-CommonEventService.md).
650
651| ID| Error Message                           |
652| -------- | ----------------------------------- |
653| 1500007  | error sending message to Common Event Service.             |
654| 1500008  | Common Event Service does not complete initialization.     |
655
656**Example**
657
658
659```ts
660import Base from '@ohos.base';
661
662CommonEventManager.setStaticSubscriberState(false).then(() => {
663    console.info(`Set static subscriber state promise success`);
664}).catch ((err:Base.BusinessError) => {
665    console.info(`Set static subscriber state promise failed, errCode: ${err.code}, errMes: ${err.message}`);
666});
667```
668