1# @ohos.commonEventManager (Common Event) (System API)
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> This topic describes only system APIs provided by the module. For details about its public APIs, see [CommonEventManager](./js-apis-commonEventManager.md).
10
11## Modules to Import
12
13```ts
14import CommonEventManager from '@ohos.commonEventManager';
15```
16
17## Support
18
19A 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.
20
21For details about the enumerations of all system common events, see [System Common Events](./common_event/commonEventManager-definitions.md).
22
23## CommonEventManager.publishAsUser<sup>
24
25publishAsUser(event: string, userId: number, callback: AsyncCallback\<void>): void
26
27Publishes a common event to a specific user. This API uses an asynchronous callback to return the result.
28
29**System capability**: SystemCapability.Notification.CommonEvent
30
31**System API**: This is a system API and cannot be called by third-party applications.
32
33**Parameters**
34
35| Name    | Type                | Mandatory| Description                              |
36| -------- | -------------------- | ---- | ---------------------------------- |
37| event    | string               | Yes  | Name of the common event to publish. For details, see [System Common Events](./common_event/commonEventManager-definitions.md).            |
38| userId   | number               | Yes  | User ID.|
39| callback | AsyncCallback\<void> | Yes  | Callback used to return the result.            |
40
41**Error codes**
42
43For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Event Error Codes](./errorcode-CommonEventService.md).
44
45| ID| Error Message                           |
46| -------- | ----------------------------------- |
47| 202      | not system app.                     |  
48| 401     | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed.      |  
49| 1500004  | not System services.                |
50| 1500007  | error sending message to Common Event Service. |
51| 1500008  | Common Event Service does not complete initialization. |
52| 1500009  | error obtaining system parameters.  |
53
54**Example**
55
56```ts
57import Base from '@ohos.base';
58
59// Callback for common event publication
60function publishCB(err:Base.BusinessError) {
61	if (err) {
62        console.error(`publishAsUser failed, code is ${err.code}, message is ${err.message}`);
63    } else {
64        console.info("publishAsUser");
65    }
66}
67
68// Specify the user to whom the common event will be published.
69let userId = 100;
70
71// Publish a common event.
72try {
73    CommonEventManager.publishAsUser("event", userId, publishCB);
74} catch (error) {
75    let err:Base.BusinessError = error as Base.BusinessError;
76    console.error(`publishAsUser failed, code is ${err.code}, message is ${err.message}`);
77}
78```
79
80## CommonEventManager.publishAsUser
81
82publishAsUser(event: string, userId: number, options: CommonEventPublishData, callback: AsyncCallback\<void>): void
83
84Publishes a common event with given attributes to a specific user. This API uses an asynchronous callback to return the result.
85
86**System capability**: SystemCapability.Notification.CommonEvent
87
88**System API**: This is a system API and cannot be called by third-party applications.
89
90**Parameters**
91
92| Name    | Type                  | Mandatory| Description                  |
93| -------- | ---------------------- | ---- | ---------------------- |
94| event    | string                 | Yes  | Name of the common event to publish. For details, see [System Common Events](./common_event/commonEventManager-definitions.md). |
95| userId   | number | Yes| User ID.|
96| options  | [CommonEventPublishData](./js-apis-inner-commonEvent-commonEventPublishData.md) | Yes  | Attributes of the common event to publish.|
97| callback | AsyncCallback\<void>   | Yes  | Callback used to return the result. |
98
99**Error codes**
100
101For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Event Error Codes](./errorcode-CommonEventService.md).
102
103| ID| Error Message                           |
104| -------- | ----------------------------------- |
105| 202      | not system app.                     |  
106| 401     | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed.      |  
107| 1500004  | not System services or System app.                |
108| 1500007  | error sending message to Common Event Service. |
109| 1500008  | Common Event Service does not complete initialization. |
110| 1500009  | error obtaining system parameters.  |
111
112**Example**
113
114
115```ts
116import Base from '@ohos.base';
117
118// Attributes of a common event.
119let options:CommonEventManager.CommonEventPublishData = {
120	code: 0,			 // Result code of the common event.
121	data: "initial data",// Result data of the common event.
122}
123
124// Callback for common event publication
125function publishCB(err:Base.BusinessError) {
126	if (err) {
127        console.error(`publishAsUser failed, code is ${err.code}, message is ${err.message}`);
128    } else {
129        console.info("publishAsUser");
130    }
131}
132
133// Specify the user to whom the common event will be published.
134let userId = 100;
135
136// Publish a common event.
137try {
138    CommonEventManager.publishAsUser("event", userId, options, publishCB);
139} catch (error) {
140    let err:Base.BusinessError = error as Base.BusinessError;
141    console.error(`publishAsUser failed, code is ${err.code}, message is ${err.message}`);
142}
143```
144
145## CommonEventManager.removeStickyCommonEvent<sup>10+</sup>
146
147removeStickyCommonEvent(event: string, callback: AsyncCallback\<void>): void
148
149Removes a sticky common event. This API uses an asynchronous callback to return the result.
150
151**System capability**: SystemCapability.Notification.CommonEvent
152
153**Required permissions**: ohos.permission.COMMONEVENT_STICKY
154
155**System API**: This is a system API and cannot be called by third-party applications.
156
157**Parameters**
158
159| Name  | Type                | Mandatory| Description                            |
160| -------- | -------------------- | ---- | -------------------------------- |
161| event    | string               | Yes  | Sticky common event to remove. For details, see [System Common Events](./common_event/commonEventManager-definitions.md).      |
162| callback | AsyncCallback\<void> | Yes  | Callback used to return the result.|
163
164**Error codes**
165
166For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Event Error Codes](./errorcode-CommonEventService.md).
167
168| ID| Error Message                           |
169| -------- | ----------------------------------- |
170| 201      | The application dose not have permission to call the interface.     |  
171| 202      | not system app.                     |  
172| 401     | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed.      |   
173| 1500004  | not system service.                 |
174| 1500007  | error sending message to Common Event Service.             |
175| 1500008  | Common Event Service does not complete initialization.     |
176
177**Example**
178
179
180```ts
181import Base from '@ohos.base';
182
183CommonEventManager.removeStickyCommonEvent("sticky_event", (err:Base.BusinessError) => {
184    if (err) {
185        console.info(`removeStickyCommonEvent failed, errCode: ${err.code}, errMes: ${err.message}`);
186        return;
187    }
188    console.info(`removeStickyCommonEvent success`);
189});
190```
191
192## CommonEventManager.removeStickyCommonEvent<sup>10+</sup>
193
194removeStickyCommonEvent(event: string): Promise\<void>
195
196Removes a sticky common event. This API uses a promise to return the result.
197
198**System capability**: SystemCapability.Notification.CommonEvent
199
200**Required permissions**: ohos.permission.COMMONEVENT_STICKY
201
202**System API**: This is a system API and cannot be called by third-party applications.
203
204**Parameters**
205
206| Name| Type  | Mandatory| Description                      |
207| ------ | ------ | ---- | -------------------------- |
208| event  | string | Yes  | Sticky common event to remove. For details, see [System Common Events](./common_event/commonEventManager-definitions.md).|
209
210**Return value**
211
212| Type          | Description                        |
213| -------------- | ---------------------------- |
214| Promise\<void> | Promise used to return the result.|
215
216**Error codes**
217
218For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Event Error Codes](./errorcode-CommonEventService.md).
219
220| ID| Error Message                           |
221| -------- | ----------------------------------- |
222| 201      | The application dose not have permission to call the interface.     |  
223| 202      | not system app.                     |  
224| 401     | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed.      | 
225| 1500004  | not system service.                 |
226| 1500007  | error sending message to Common Event Service.             |
227| 1500008  | Common Event Service does not complete initialization.     |
228
229**Example**
230
231
232```ts
233import Base from '@ohos.base';
234
235CommonEventManager.removeStickyCommonEvent("sticky_event").then(() => {
236    console.info(`removeStickyCommonEvent success`);
237}).catch ((err:Base.BusinessError) => {
238    console.info(`removeStickyCommonEvent failed, errCode: ${err.code}, errMes: ${err.message}`);
239});
240```
241
242## CommonEventManager.setStaticSubscriberState<sup>10+</sup>
243
244setStaticSubscriberState(enable: boolean, callback: AsyncCallback\<void>): void;
245
246Enables or disables static subscription for the current application. This API uses an asynchronous callback to return the result.
247
248**Model restriction**: This API can be used only in the stage model.
249
250**System capability**: SystemCapability.Notification.CommonEvent
251
252**System API**: This is a system API and cannot be called by third-party applications.
253
254**Parameters**
255
256| Name| Type  | Mandatory| Description                      |
257| ------ | ------ | ---- | -------------------------- |
258| enable  | boolean | Yes  | Whether static subscription is enabled.<br> **true**: enabled.<br>**false**: disabled.|
259| callback  | AsyncCallback\<void> | Yes  | Callback used to return the result.|
260
261**Error codes**
262
263For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Event Error Codes](./errorcode-CommonEventService.md).
264
265| ID| Error Message                           |
266| -------- | ----------------------------------- |
267| 202      | not system app.                     |  
268| 401     | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed.      | 
269| 1500007  | error sending message to Common Event Service.             |
270| 1500008  | Common Event Service does not complete initialization.     |
271
272**Example**
273
274
275```ts
276import Base from '@ohos.base';
277
278CommonEventManager.setStaticSubscriberState(true, (err:Base.BusinessError) => {
279    if (!err) {
280        console.info(`setStaticSubscriberState failed, err is null.`);
281        return;
282    }
283    if (err.code !== undefined && err.code != null) {
284        console.info(`setStaticSubscriberState failed, errCode: ${err.code}, errMes: ${err.message}`);
285        return;
286    }
287    console.info(`setStaticSubscriberState success`);
288});
289```
290
291## CommonEventManager.setStaticSubscriberState<sup>10+</sup>
292
293setStaticSubscriberState(enable: boolean): Promise\<void>;
294
295Enables or disables static subscription for the current application. This API uses a promise to return the result.
296
297**Model restriction**: This API can be used only in the stage model.
298
299**System capability**: SystemCapability.Notification.CommonEvent
300
301**System API**: This is a system API and cannot be called by third-party applications.
302
303**Parameters**
304
305| Name| Type  | Mandatory| Description                      |
306| ------ | ------ | ---- | -------------------------- |
307| enable  | boolean | Yes  | Whether static subscription is enabled.<br> **true**: enabled.<br>**false**: disabled.|
308
309**Return value**
310
311| Type          | Description                        |
312| -------------- | ---------------------------- |
313| Promise\<void> |  Promise that returns no value.|
314
315**Error codes**
316
317For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Event Error Codes](./errorcode-CommonEventService.md).
318
319| ID| Error Message                           |
320| -------- | ----------------------------------- |
321| 202      | not system app.                     |  
322| 401     | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed.      | 
323| 1500007  | error sending message to Common Event Service.             |
324| 1500008  | Common Event Service does not complete initialization.     |
325
326**Example**
327
328
329```ts
330import Base from '@ohos.base';
331
332CommonEventManager.setStaticSubscriberState(false).then(() => {
333    console.info(`setStaticSubscriberState success`);
334}).catch ((err:Base.BusinessError) => {
335    console.info(`setStaticSubscriberState failed, errCode: ${err.code}, errMes: ${err.message}`);
336});
337```
338
339## CommonEventManager.setStaticSubscriberState<sup>12+</sup>
340
341setStaticSubscriberState(enable: boolean, events?: Array<string>): Promise<void>
342
343Enables or disables the static subscription event for the current application and records the event name. This API uses a promise to return the result.
344
345**Model restriction**: This API can be used only in the stage model.
346
347**System capability**: SystemCapability.Notification.CommonEvent
348
349**System API**: This is a system API.
350
351**Parameters**
352
353| Name| Type         | Mandatory| Description                                                |
354| ------ | ------------- | ---- | ---------------------------------------------------- |
355| enable | boolean       | Yes  | Whether static subscription is enabled.<br> **true**: enabled.<br>**false**: disabled.|
356| events | array<string> | No  | Name of a recorded event.                                  |
357
358**Return value**
359
360| Type          | Description                                |
361| -------------- | ------------------------------------ |
362| Promise\<void> | Promise that returns no value.|
363
364**Error codes**
365
366For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Event Error Codes](./errorcode-CommonEventService.md).
367
368| ID| Error Message                                              |
369| -------- | ------------------------------------------------------ |
370| 202      | not system app.                     |  
371| 401     | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed.      | 
372| 1500007  | error sending message to Common Event Service.         |
373| 1500008  | Common Event Service does not complete initialization. |
374
375**Example**
376
377
378```ts
379import Base from '@ohos.base'
380import promptAction from '@ohos.promptAction'
381import CommonEventManager from '@ohos.commonEventManager'
382
383let evenName: string[] = ['usual.event.SEND_DATA'];
384CommonEventManager.setStaticSubscriberState(true, evenName).then(() => {
385  try {
386    promptAction.showToast({
387      message: 'app.string.static_subscribe_enabled',
388      duration: 2000,
389    });
390  } catch (error) {
391    console.error(`showToast error code is ${error.code}, message is ${error.message}`);
392  }
393  console.info(`setStaticSubscriberState success, state is ${true}`);
394}).catch((err: Base.BusinessError) => {
395  console.info(`setStaticSubscriberState failed, errCode: ${err.code}, errMes: ${err.message}`);
396});
397```
398