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