1# @ohos.commonEventManager (Common Event) (System API)
2
3This module provides common event capabilities, including publishing, subscribing to, and unsubscribing 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 '@kit.BasicServicesKit';
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  | A third-party application cannot send system common events.                |
50| 1500007  | Failed to send the message to the common event service. |
51| 1500008  | Failed to initialize the common event service. |
52| 1500009  | Failed to obtain system parameters.  |
53
54**Example**
55
56```ts
57import { BusinessError } from '@kit.BasicServicesKit';
58
59// Callback for common event publication.
60function publishCB(err: 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: BusinessError = error as 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  | A third-party application cannot send system common events.                |
108| 1500007  | Failed to send the message to the common event service. |
109| 1500008  | Failed to initialize the common event service. |
110| 1500009  | Failed to obtain system parameters.  |
111
112**Example**
113
114```ts
115import { BusinessError } from '@kit.BasicServicesKit';
116
117// Attributes of a common event.
118let options:commonEventManager.CommonEventPublishData = {
119  code: 0,			 // Result code of the common event.
120  data: "initial data",// Result data of the common event.
121}
122// Callback for common event publication.
123function publishCB(err: BusinessError) {
124  if (err) {
125    console.error(`publishAsUser failed, code is ${err.code}, message is ${err.message}`);
126  } else {
127    console.info("publishAsUser");
128  }
129}
130// Specify the user to whom the common event will be published.
131let userId = 100;
132// Publish a common event.
133try {
134  commonEventManager.publishAsUser("event", userId, options, publishCB);
135} catch (error) {
136  let err: BusinessError = error as BusinessError;
137  console.error(`publishAsUser failed, code is ${err.code}, message is ${err.message}`);
138}
139```
140
141## commonEventManager.removeStickyCommonEvent<sup>10+</sup>
142
143removeStickyCommonEvent(event: string, callback: AsyncCallback\<void>): void
144
145Removes a sticky common event. This API uses an asynchronous callback to return the result.
146
147**System capability**: SystemCapability.Notification.CommonEvent
148
149**Required permissions**: ohos.permission.COMMONEVENT_STICKY
150
151**System API**: This is a system API and cannot be called by third-party applications.
152
153**Parameters**
154
155| Name  | Type                | Mandatory| Description                            |
156| -------- | -------------------- | ---- | -------------------------------- |
157| event    | string               | Yes  | Sticky common event to remove. For details, see [System Common Events](./common_event/commonEventManager-definitions.md).      |
158| callback | AsyncCallback\<void> | Yes  | Callback used to return the result.|
159
160**Error codes**
161
162For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Event Error Codes](./errorcode-CommonEventService.md).
163
164| ID| Error Message                           |
165| -------- | ----------------------------------- |
166| 201      | The application does not have permission to call the interface.    |
167| 202      | not system app.                     |
168| 401     | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed.      |
169| 1500004  | A third-party application cannot send system common events.                |
170| 1500007  | Failed to send the message to the common event service.             |
171| 1500008  | Failed to initialize the common event service.     |
172
173**Example**
174
175```ts
176import { BusinessError } from '@kit.BasicServicesKit';
177
178commonEventManager.removeStickyCommonEvent("sticky_event", (err: BusinessError) => {
179  if (err) {
180    console.error(`removeStickyCommonEvent failed, errCode: ${err.code}, errMes: ${err.message}`);
181    return;
182  }
183  console.info(`removeStickyCommonEvent success`);
184});
185```
186
187## commonEventManager.removeStickyCommonEvent<sup>10+</sup>
188
189removeStickyCommonEvent(event: string): Promise\<void>
190
191Removes a sticky common event. This API uses a promise to return the result.
192
193**System capability**: SystemCapability.Notification.CommonEvent
194
195**Required permissions**: ohos.permission.COMMONEVENT_STICKY
196
197**System API**: This is a system API and cannot be called by third-party applications.
198
199**Parameters**
200
201| Name| Type  | Mandatory| Description                      |
202| ------ | ------ | ---- | -------------------------- |
203| event  | string | Yes  | Sticky common event to remove. For details, see [System Common Events](./common_event/commonEventManager-definitions.md).|
204
205**Return value**
206
207| Type          | Description                        |
208| -------------- | ---------------------------- |
209| Promise\<void> | Promise used to return the result.|
210
211**Error codes**
212
213For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Event Error Codes](./errorcode-CommonEventService.md).
214
215| ID| Error Message                           |
216| -------- | ----------------------------------- |
217| 201      | The application does not have permission to call the interface.    |
218| 202      | not system app.                     |
219| 401     | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed.      |
220| 1500004  | A third-party application cannot send system common events.                |
221| 1500007  | Failed to send the message to the common event service.             |
222| 1500008  | Failed to initialize the common event service.     |
223
224**Example**
225
226```ts
227import { BusinessError } from '@kit.BasicServicesKit';
228
229commonEventManager.removeStickyCommonEvent("sticky_event").then(() => {
230  console.info(`removeStickyCommonEvent success`);
231}).catch ((err: BusinessError) => {
232  console.error(`removeStickyCommonEvent failed, errCode: ${err.code}, errMes: ${err.message}`);
233});
234```
235
236## commonEventManager.setStaticSubscriberState<sup>10+</sup>
237
238setStaticSubscriberState(enable: boolean, callback: AsyncCallback\<void>): void;
239
240Enables or disables static subscription for the current application. This API uses an asynchronous callback to return the result.
241
242**Model restriction**: This API can be used only in the stage model.
243
244**System capability**: SystemCapability.Notification.CommonEvent
245
246**System API**: This is a system API and cannot be called by third-party applications.
247
248**Parameters**
249
250| Name| Type  | Mandatory| Description                      |
251| ------ | ------ | ---- | -------------------------- |
252| enable  | boolean | Yes  | Whether static subscription is enabled.<br>**true**: enabled.<br>**false**: disabled. |
253| callback  | AsyncCallback\<void> | Yes  | Callback used to return the result.|
254
255**Error codes**
256
257For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Event Error Codes](./errorcode-CommonEventService.md).
258
259| ID| Error Message                           |
260| -------- | ----------------------------------- |
261| 202      | not system app.                     |
262| 401     | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed.      |
263| 1500007  | Failed to send the message to the common event service.             |
264| 1500008  | Failed to initialize the common event service.     |
265
266**Example**
267
268```ts
269import { BusinessError } from '@kit.BasicServicesKit';
270
271commonEventManager.setStaticSubscriberState(true, (err: BusinessError) => {
272  if (err) {
273    console.error(`setStaticSubscriberState failed, errCode: ${err.code}, errMes: ${err.message}`);
274    return;
275  }
276  console.info(`setStaticSubscriberState success`);
277});
278```
279
280## commonEventManager.setStaticSubscriberState<sup>10+</sup>
281
282setStaticSubscriberState(enable: boolean): Promise\<void>;
283
284Enables or disables static subscription for the current application. This API uses a promise to return the result.
285
286**Model restriction**: This API can be used only in the stage model.
287
288**System capability**: SystemCapability.Notification.CommonEvent
289
290**System API**: This is a system API and cannot be called by third-party applications.
291
292**Parameters**
293
294| Name| Type  | Mandatory| Description                      |
295| ------ | ------ | ---- | -------------------------- |
296| enable  | boolean | Yes  | Whether static subscription is enabled.<br>**true**: enabled.<br>**false**: disabled. |
297
298**Return value**
299
300| Type          | Description                        |
301| -------------- | ---------------------------- |
302| Promise\<void> |  Promise that returns no value.|
303
304**Error codes**
305
306For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Event Error Codes](./errorcode-CommonEventService.md).
307
308| ID| Error Message                           |
309| -------- | ----------------------------------- |
310| 202      | not system app.                     |
311| 401     | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed.      |
312| 1500007  | Failed to send the message to the common event service.             |
313| 1500008  | Failed to initialize the common event service.     |
314
315**Example**
316
317
318```ts
319import { BusinessError } from '@kit.BasicServicesKit';
320
321commonEventManager.setStaticSubscriberState(false).then(() => {
322  console.info(`setStaticSubscriberState success`);
323}).catch ((err: BusinessError) => {
324  console.error(`setStaticSubscriberState failed, errCode: ${err.code}, errMes: ${err.message}`);
325});
326```
327
328## commonEventManager.setStaticSubscriberState<sup>12+</sup>
329
330setStaticSubscriberState(enable: boolean, events?: Array\<string>): Promise\<void>
331
332Enables or disables the static subscription event for the current application and records the event name. This API uses a promise to return the result.
333
334**Model restriction**: This API can be used only in the stage model.
335
336**System capability**: SystemCapability.Notification.CommonEvent
337
338**System API**: This is a system API.
339
340**Parameters**
341
342| Name| Type         | Mandatory| Description                                                |
343| ------ | ------------- | ---- | ---------------------------------------------------- |
344| enable | boolean       | Yes  | Whether static subscription is enabled.<br>**true**: enabled.<br>**false**: disabled. |
345| events | Array\<string> | No  | Name of a recorded event.                                  |
346
347**Return value**
348
349| Type          | Description                                |
350| -------------- | ------------------------------------ |
351| Promise\<void> | Promise that returns no value.|
352
353**Error codes**
354
355For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Event Error Codes](./errorcode-CommonEventService.md).
356
357| ID| Error Message                                              |
358| -------- | ------------------------------------------------------ |
359| 202      | not system app.                     |
360| 401     | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed.      |
361| 1500007  | Failed to send the message to the common event service.        |
362| 1500008  | Failed to initialize the common event service. |
363
364**Example**
365
366```ts
367import { BusinessError } from '@kit.BasicServicesKit';
368import { promptAction } from '@kit.ArkUI';
369
370let evenName: string[] = ['usual.event.SEND_DATA'];
371commonEventManager.setStaticSubscriberState(true, evenName).then(() => {
372  try {
373    promptAction.showToast({
374      message: 'app.string.static_subscribe_enabled',
375      duration: 2000,
376    });
377  } catch (error) {
378    console.error(`showToast error code is ${error.code}, message is ${error.message}`);
379  }
380  console.info(`setStaticSubscriberState success, state is ${true}`);
381}).catch((err: BusinessError) => {
382  console.error(`setStaticSubscriberState failed, errCode: ${err.code}, errMes: ${err.message}`);
383});
384```
385