• 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, as well obtaining and setting the common event result code and result data.
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. This API uses an asynchronous callback to return the result.
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 used to return the result.|
35
36**Error codes**
37For details about the error codes, see [Event Error Codes](../errorcodes/errorcode-CommonEventService.md).
38
39| ID| Error Message                           |
40| -------- | ----------------------------------- |
41| 1500004  | not System services or System app.                |
42| 1500007  | error sending message to Common Event Service. |
43| 1500008  | Common Event Service does not complete initialization. |
44| 1500009  | error obtaining system parameters.  |
45
46**Example**
47
48```ts
49// Callback for common event publication
50function publishCallBack(err) {
51	if (err) {
52        console.error("publish failed " + JSON.stringify(err));
53    } else {
54        console.info("publish");
55    }
56}
57
58// Publish a common event.
59try {
60    CommonEventManager.publish("event", publishCallBack);
61} catch(err) {
62    console.error('publish failed, catch error' + JSON.stringify(err));
63}
64```
65
66## CommonEventManager.publish
67
68publish(event: string, options: CommonEventPublishData, callback: AsyncCallback\<void>): void
69
70Publishes a common event with given attributes. This API uses an asynchronous callback to return the result.
71
72**System capability**: SystemCapability.Notification.CommonEvent
73
74**Parameters**
75
76| Name    | Type                  | Mandatory| Description                  |
77| -------- | ---------------------- | ---- | ---------------------- |
78| event    | string                 | Yes  | Name of the common event to publish. |
79| options  | [CommonEventPublishData](./js-apis-inner-commonEvent-commonEventPublishData.md) | Yes  | Attributes of the common event to publish.|
80| callback | syncCallback\<void>   | Yes  | Callback used to return the result. |
81
82**Error codes**
83| ID| Error Message                           |
84| -------- | ----------------------------------- |
85| 1500004  | not System services or System app.                |
86| 1500007  | error sending message to Common Event Service. |
87| 1500008  | Common Event Service does not complete initialization. |
88| 1500009  | error obtaining system parameters.  |
89
90**Example**
91
92```ts
93// Attributes of a common event.
94var options = {
95	code: 0,			 // Result code of the common event.
96	data: "initial data",// Result data of the common event.
97	isOrdered: true	 // The common event is an ordered one.
98}
99
100// Callback for common event publication
101function publishCallBack(err) {
102	if (err) {
103        console.error("publish failed " + JSON.stringify(err));
104    } else {
105        console.info("publish");
106    }
107}
108
109// Publish a common event.
110try {
111    CommonEventManager.publish("event", options, publishCallBack);
112} catch (err) {
113    console.error('publish failed, catch error' + JSON.stringify(err));
114}
115```
116
117
118
119## CommonEventManager.publishAsUser<sup>
120
121publishAsUser(event: string, userId: number, callback: AsyncCallback\<void>): void
122
123Publishes a common event to a specific user. This API uses an asynchronous callback to return the result.
124
125**System capability**: SystemCapability.Notification.CommonEvent
126
127**System API**: This is a system API and cannot be called by third-party applications.
128
129**Parameters**
130
131| Name    | Type                | Mandatory| Description                              |
132| -------- | -------------------- | ---- | ---------------------------------- |
133| event    | string               | Yes  | Name of the common event to publish.            |
134| userId   | number               | Yes  | User ID.|
135| callback | AsyncCallback\<void> | Yes  | Callback used to return the result.            |
136
137**Error codes**
138| ID| Error Message                           |
139| -------- | ----------------------------------- |
140| 1500004  | not System services or System app.              |
141| 1500007  | error sending message to Common Event Service. |
142| 1500008  | Common Event Service does not complete initialization. |
143| 1500009  | error obtaining system parameters.  |
144
145**Example**
146
147```ts
148// Callback for common event publication
149function publishAsUserCallBack(err) {
150	if (err) {
151        console.error("publishAsUser failed " + JSON.stringify(err));
152    } else {
153        console.info("publishAsUser");
154    }
155}
156
157// Specify the user to whom the common event will be published.
158var userId = 100;
159
160// Publish a common event.
161try {
162    CommonEventManager.publishAsUser("event", userId, publishAsUserCallBack);
163} catch (err) {
164    console.error('publishAsUser failed, catch error' + JSON.stringify(err));
165}
166```
167
168
169
170## CommonEventManager.publishAsUser
171
172publishAsUser(event: string, userId: number, options: CommonEventPublishData, callback: AsyncCallback\<void>): void
173
174Publishes a common event with given attributes to a specific user. This API uses an asynchronous callback to return the result.
175
176**System capability**: SystemCapability.Notification.CommonEvent
177
178**System API**: This is a system API and cannot be called by third-party applications.
179
180**Parameters**
181
182| Name    | Type                  | Mandatory| Description                  |
183| -------- | ---------------------- | ---- | ---------------------- |
184| event    | string                 | Yes  | Name of the common event to publish. |
185| userId   | number | Yes| User ID.|
186| options  | [CommonEventPublishData](./js-apis-inner-commonEvent-commonEventPublishData.md) | Yes  | Attributes of the common event to publish.|
187| callback | AsyncCallback\<void>   | Yes  | Callback used to return the result. |
188
189**Error codes**
190| ID| Error Message                           |
191| -------- | ----------------------------------- |
192| 1500004  | not System services or System app.                |
193| 1500007  | error sending message to Common Event Service. |
194| 1500008  | Common Event Service does not complete initialization. |
195| 1500009  | error obtaining system parameters.  |
196
197**Example**
198
199```ts
200// Attributes of a common event.
201var options = {
202	code: 0,			 // Result code of the common event.
203	data: "initial data",// Result data of the common event.
204}
205
206// Callback for common event publication
207function publishAsUserCallBack(err) {
208	if (err) {
209        console.error("publishAsUser failed " + JSON.stringify(err));
210    } else {
211        console.info("publishAsUser");
212    }
213}
214
215// Specify the user to whom the common event will be published.
216var userId = 100;
217
218// Publish a common event.
219try {
220    CommonEventManager.publishAsUser("event", userId, options, publishAsUserCallBack);
221} catch (err) {
222    console.error('publishAsUser failed, catch error' + JSON.stringify(err));
223}
224```
225
226
227
228## CommonEventManager.createSubscriber
229
230createSubscriber(subscribeInfo: CommonEventSubscribeInfo, callback: AsyncCallback\<CommonEventSubscriber>): void
231
232Creates a subscriber. This API uses an asynchronous callback to return the result.
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| callback      | AsyncCallback\<[CommonEventSubscriber](./js-apis-inner-commonEvent-commonEventSubscriber.md)> | Yes  | Callback used to return the result.|
242
243**Example**
244
245
246```ts
247var subscriber; // Used to save the created subscriber object for subsequent subscription and unsubscription.
248
249// Subscriber information.
250var subscribeInfo = {
251    events: ["event"]
252};
253
254// Callback for subscriber creation.
255function createSubscriberCallBack(err, commonEventSubscriber) {
256    if(!err) {
257        console.info("createSubscriber");
258        subscriber = commonEventSubscriber;
259    } else {
260        console.error("createSubscriber failed " + JSON.stringify(err));
261    }
262}
263
264// Create a subscriber.
265try {
266    CommonEventManager.createSubscriber(subscribeInfo, createSubscriberCallBack);
267} catch (err) {
268    console.error('createSubscriber failed, catch error' + JSON.stringify(err));
269}
270```
271
272
273
274## CommonEventManager.createSubscriber
275
276createSubscriber(subscribeInfo: CommonEventSubscribeInfo): Promise\<CommonEventSubscriber>
277
278Creates a subscriber. This API uses a promise to return the result.
279
280**System capability**: SystemCapability.Notification.CommonEvent
281
282**Parameters**
283
284| Name         | Type                                                 | Mandatory| Description          |
285| ------------- | ----------------------------------------------------- | ---- | -------------- |
286| subscribeInfo | [CommonEventSubscribeInfo](./js-apis-inner-commonEvent-commonEventSubscribeInfo.md) | Yes  | Subscriber information.|
287
288**Return value**
289| Type                                                     | Description            |
290| --------------------------------------------------------- | ---------------- |
291| Promise\<[CommonEventSubscriber](./js-apis-inner-commonEvent-commonEventSubscriber.md)> | Promise used to return the subscriber object.|
292
293**Example**
294
295```ts
296var subscriber; // Used to save the created subscriber object for subsequent subscription and unsubscription.
297
298// Subscriber information.
299var subscribeInfo = {
300	events: ["event"]
301};
302
303// Create a subscriber.
304try {
305    CommonEventManager.createSubscriber(subscribeInfo).then((commonEventSubscriber) => {
306    console.info("createSubscriber");
307    subscriber = commonEventSubscriber;
308}).catch((err) => {
309    console.error("createSubscriber failed " + JSON.stringify(err));
310});
311} catch(err) {
312    console.error('createSubscriber failed, catch error' + JSON.stringify(err));
313}
314
315```
316
317
318
319## CommonEventManager.subscribe
320
321subscribe(subscriber: CommonEventSubscriber, callback: AsyncCallback\<CommonEventData>): void
322
323Subscribes to common events. This API uses an asynchronous callback to return the result.
324
325**System capability**: SystemCapability.Notification.CommonEvent
326
327**Parameters**
328
329| Name      | Type                                               | Mandatory| Description                            |
330| ---------- | ---------------------------------------------------- | ---- | -------------------------------- |
331| subscriber | [CommonEventSubscriber](./js-apis-inner-commonEvent-commonEventSubscriber.md)     | Yes  | Subscriber object.                |
332| callback   | AsyncCallback\<[CommonEventData](./js-apis-inner-commonEvent-commonEventData.md)> | Yes  | Callback used to return the result.|
333
334**Error codes**
335
336 For details about the error codes, see [Event Error Codes](../errorcodes/errorcode-CommonEventService.md).
337
338| ID| Error Message                           |
339| -------- | ----------------------------------- |
340| 801  | capability not supported.               |
341| 1500007  | error sending message to Common Event Service. |
342| 1500008  | Common Event Service does not complete initialization. |
343
344**Example**
345
346```ts
347// Subscriber information.
348var subscriber; // Used to save the created subscriber object for subsequent subscription and unsubscription.
349
350// Subscriber information.
351var subscribeInfo = {
352    events: ["event"]
353};
354
355// Callback for common event subscription.
356function SubscribeCallBack(err, data) {
357    if (err) {
358        console.error("subscribe failed " + JSON.stringify(err));
359    } else {
360        console.info("subscribe ");
361    }
362}
363
364// Callback for subscriber creation.
365function createSubscriberCallBack(err, commonEventSubscriber) {
366    if(!err) {
367        console.info("createSubscriber");
368        subscriber = commonEventSubscriber;
369        // Subscribe to a common event.
370        try {
371            CommonEventManager.subscribe(subscriber, SubscribeCallBack);
372        } catch (err) {
373            console.error("createSubscriber failed " + JSON.stringify(err));
374        }
375    } else {
376        console.error("createSubscriber failed " + JSON.stringify(err));
377    }
378}
379
380// Create a subscriber.
381try {
382    CommonEventManager.createSubscriber(subscribeInfo, createSubscriberCallBack);
383} catch (err) {
384    console.error('createSubscriber failed, catch error' + JSON.stringify(err));
385}
386```
387
388
389
390## CommonEventManager.unsubscribe
391
392unsubscribe(subscriber: CommonEventSubscriber, callback?: AsyncCallback\<void>): void
393
394Unsubscribes from common events. This API uses an asynchronous callback to return the result.
395
396**System capability**: SystemCapability.Notification.CommonEvent
397
398**Parameters**
399
400| Name      | Type                                            | Mandatory| Description                    |
401| ---------- | ----------------------------------------------- | ---- | ------------------------ |
402| subscriber | [CommonEventSubscriber](./js-apis-inner-commonEvent-commonEventSubscriber.md) | Yes  | Subscriber object.        |
403| callback   | AsyncCallback\<void>                            | No  | Callback used to return the result.|
404
405**Error codes**
406
407 For details about the error codes, see [Event Error Codes](../errorcodes/errorcode-CommonEventService.md).
408
409| ID| Error Message                           |
410| -------- | ----------------------------------- |
411| 801  | capability not supported.               |
412| 1500007  | error sending message to Common Event Service. |
413| 1500008  | Common Event Service does not complete initialization. |
414
415**Example**
416
417```ts
418var subscriber; // Used to save the created subscriber object for subsequent subscription and unsubscription.
419// Subscriber information.
420var subscribeInfo = {
421    events: ["event"]
422};
423// Callback for common event subscription.
424function subscribeCallBack(err, data) {
425    if (err) {
426        console.info("subscribe failed " + JSON.stringify(err));
427    } else {
428        console.info("subscribe");
429    }
430}
431// Callback for subscriber creation.
432function createSubscriberCallBack(err, commonEventSubscriber) {
433    if (err) {
434        console.info("createSubscriber failed " + JSON.stringify(err));
435    } else {
436        console.info("createSubscriber");
437        subscriber = commonEventSubscriber;
438        // Subscribe to a common event.
439        try {
440            CommonEventManager.subscribe(subscriber, subscribeCallBack);
441        } catch(err) {
442            console.info("subscribe failed " + JSON.stringify(err));
443        }
444    }
445}
446// Callback for common event unsubscription.
447function unsubscribeCallBack(err) {
448    if (err) {
449        console.info("unsubscribe failed " + JSON.stringify(err));
450    } else {
451        console.info("unsubscribe");
452    }
453}
454// Create a subscriber.
455try {
456    CommonEventManager.createSubscriber(subscribeInfo, createSubscriberCallBack);
457} catch (err) {
458    console.info("createSubscriber failed " + JSON.stringify(err));
459}
460
461// Unsubscribe from the common event.
462try {
463    CommonEventManager.unsubscribe(subscriber, unsubscribeCallBack);
464} catch (err) {
465    console.info("unsubscribe failed " + JSON.stringify(err));
466}
467```
468
469## CommonEventData
470
471**System capability**: SystemCapability.Notification.CommonEvent
472
473| Name      | Type                | Readable| Writable| Description                                                   |
474| ---------- |-------------------- | ---- | ---- |  ------------------------------------------------------- |
475| event      | string               | Yes | No | Name of the common event that is being received.                             |
476| bundleName | string               | Yes | No | Bundle name.                                             |
477| code       | number               | Yes | No | Result code of the common event, which is used to transfer data of the int type.          |
478| data       | string               | Yes | No | Custom result data of the common event, which is used to transfer data of the string type.|
479| parameters | {[key: string]: any} | Yes | No | Additional information about the common event.                                 |
480
481
482## CommonEventPublishData
483
484**System capability**: SystemCapability.Notification.CommonEvent
485
486| Name                 | Type                | Readable| Writable| Description                        |
487| --------------------- | -------------------- | ---- | ---- | ---------------------------- |
488| bundleName            | string               | Yes | No | Bundle name.                  |
489| code                  | number               | Yes | No | Result code of the common event.      |
490| data                  | string               | Yes | No | Custom result data of the common event.|
491| subscriberPermissions | Array\<string>       | Yes | No | Permissions required for subscribers to receive the common event.            |
492| isOrdered             | boolean              | Yes | No | Whether the common event is an ordered one.          |
493| isSticky              | boolean              | Yes | No | Whether the common event is a sticky one. Only system applications and system services are allowed to send sticky events.|
494| parameters            | {[key: string]: any} | Yes | No | Additional information about the common event.      |
495
496## CommonEventSubscribeInfo
497
498**System capability**: SystemCapability.Notification.CommonEvent
499
500| Name               | Type          | Readable| Writable| Description                                                        |
501| ------------------- | -------------- | ---- | ---- | ------------------------------------------------------------ |
502| events              | Array\<string> | Yes | No | Name of the common event to publish.                                        |
503| publisherPermission | string         | Yes | No | Permissions required for publishers to publish the common event.                                            |
504| publisherDeviceId   | string         | Yes | No | Device ID. The value must be the ID of an existing device on the same network.            |
505| userId              | number         | Yes | No | User ID. The default value is the ID of the current user. If this parameter is specified, the value must be an existing user ID in the system.|
506| priority            | number         | Yes | No | Subscriber priority. The value ranges from -100 to +1000.                    |
507