• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 definitions of all system common events, see [System Common Events](./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.            |
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 [Event Error Codes](./errorcode-CommonEventService.md).
44
45| ID| Error Message                           |
46| -------- | ----------------------------------- |
47| 1500004  | not System services.                |
48| 1500007  | error sending message to Common Event Service. |
49| 1500008  | Common Event Service does not complete initialization. |
50| 1500009  | error obtaining system parameters.  |
51
52**Example**
53
54```ts
55import Base from '@ohos.base';
56
57// Callback for common event publication
58function publishCB(err:Base.BusinessError) {
59	if (err) {
60        console.error(`publishAsUser failed, code is ${err.code}, message is ${err.message}`);
61    } else {
62        console.info("publishAsUser");
63    }
64}
65
66// Specify the user to whom the common event will be published.
67let userId = 100;
68
69// Publish a common event.
70try {
71    CommonEventManager.publishAsUser("event", userId, publishCB);
72} catch (error) {
73    let err:Base.BusinessError = error as Base.BusinessError;
74    console.error(`publishAsUser failed, code is ${err.code}, message is ${err.message}`);
75}
76```
77
78## CommonEventManager.publishAsUser
79
80publishAsUser(event: string, userId: number, options: CommonEventPublishData, callback: AsyncCallback\<void>): void
81
82Publishes a common event with given attributes to a specific user. This API uses an asynchronous callback to return the result.
83
84**System capability**: SystemCapability.Notification.CommonEvent
85
86**System API**: This is a system API and cannot be called by third-party applications.
87
88**Parameters**
89
90| Name    | Type                  | Mandatory| Description                  |
91| -------- | ---------------------- | ---- | ---------------------- |
92| event    | string                 | Yes  | Name of the common event to publish. |
93| userId   | number | Yes| User ID.|
94| options  | [CommonEventPublishData](./js-apis-inner-commonEvent-commonEventPublishData.md) | Yes  | Attributes of the common event to publish.|
95| callback | AsyncCallback\<void>   | Yes  | Callback used to return the result. |
96
97**Error codes**
98
99For details about the error codes, see [Event Error Codes](./errorcode-CommonEventService.md).
100
101| ID| Error Message                           |
102| -------- | ----------------------------------- |
103| 1500004  | not System services or System app.                |
104| 1500007  | error sending message to Common Event Service. |
105| 1500008  | Common Event Service does not complete initialization. |
106| 1500009  | error obtaining system parameters.  |
107
108**Example**
109
110
111```ts
112import Base from '@ohos.base';
113
114// Attributes of a common event.
115let options:CommonEventManager.CommonEventPublishData = {
116	code: 0,			 // Result code of the common event.
117	data: "initial data",// Result data of the common event.
118}
119
120// Callback for common event publication
121function publishCB(err:Base.BusinessError) {
122	if (err) {
123        console.error(`publishAsUser failed, code is ${err.code}, message is ${err.message}`);
124    } else {
125        console.info("publishAsUser");
126    }
127}
128
129// Specify the user to whom the common event will be published.
130let userId = 100;
131
132// Publish a common event.
133try {
134    CommonEventManager.publishAsUser("event", userId, options, publishCB);
135} catch (error) {
136    let err:Base.BusinessError = error as Base.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.      |
158| callback | AsyncCallback\<void> | Yes  | Callback used to return the result.|
159
160**Error codes**
161
162For details about the error codes, see [Event Error Codes](./errorcode-CommonEventService.md).
163
164| ID| Error Message                           |
165| -------- | ----------------------------------- |
166| 1500004  | not system service.                 |
167| 1500007  | error sending message to Common Event Service.             |
168| 1500008  | Common Event Service does not complete initialization.     |
169
170**Example**
171
172
173```ts
174import Base from '@ohos.base';
175
176CommonEventManager.removeStickyCommonEvent("sticky_event", (err:Base.BusinessError) => {
177    if (err) {
178        console.info(`Remove sticky event AsyncCallback failed, errCode: ${err.code}, errMes: ${err.message}`);
179        return;
180    }
181    console.info(`Remove sticky event AsyncCallback success`);
182});
183```
184
185## CommonEventManager.removeStickyCommonEvent<sup>10+</sup>
186
187removeStickyCommonEvent(event: string): Promise\<void>
188
189Removes a sticky common event. This API uses a promise to return the result.
190
191**System capability**: SystemCapability.Notification.CommonEvent
192
193**Required permissions**: ohos.permission.COMMONEVENT_STICKY
194
195**System API**: This is a system API and cannot be called by third-party applications.
196
197**Parameters**
198
199| Name| Type  | Mandatory| Description                      |
200| ------ | ------ | ---- | -------------------------- |
201| event  | string | Yes  | Sticky common event to remove.|
202
203**Return value**
204
205| Type          | Description                        |
206| -------------- | ---------------------------- |
207| Promise\<void> | Promise used to return the result.|
208
209**Error codes**
210
211For details about the error codes, see [Event Error Codes](./errorcode-CommonEventService.md).
212
213| ID| Error Message                           |
214| -------- | ----------------------------------- |
215| 1500004  | not system service.                 |
216| 1500007  | error sending message to Common Event Service.             |
217| 1500008  | Common Event Service does not complete initialization.     |
218
219**Example**
220
221
222```ts
223import Base from '@ohos.base';
224
225CommonEventManager.removeStickyCommonEvent("sticky_event").then(() => {
226    console.info(`Remove sticky event AsyncCallback success`);
227}).catch ((err:Base.BusinessError) => {
228    console.info(`Remove sticky event AsyncCallback failed, errCode: ${err.code}, errMes: ${err.message}`);
229});
230```
231
232## CommonEventManager.setStaticSubscriberState<sup>10+</sup>
233
234setStaticSubscriberState(enable: boolean, callback: AsyncCallback\<void>): void;
235
236Enables or disables static subscription for the current application. This API uses an asynchronous callback to return the result.
237
238**Model restriction**: This API can be used only in the stage model.
239
240**System capability**: SystemCapability.Notification.CommonEvent
241
242**System API**: This is a system API and cannot be called by third-party applications.
243
244**Parameters**
245
246| Name| Type  | Mandatory| Description                      |
247| ------ | ------ | ---- | -------------------------- |
248| enable  | boolean | Yes  | Whether static subscription is enabled.<br> **true**: enabled.<br>**false**: disabled.|
249| callback  | AsyncCallback\<void> | Yes  | Callback used to return the result.|
250
251**Error codes**
252
253For details about the error codes, see [Event Error Codes](./errorcode-CommonEventService.md).
254
255| ID| Error Message                           |
256| -------- | ----------------------------------- |
257| 1500007  | error sending message to Common Event Service.             |
258| 1500008  | Common Event Service does not complete initialization.     |
259
260**Example**
261
262
263```ts
264import Base from '@ohos.base';
265
266CommonEventManager.setStaticSubscriberState(true, (err:Base.BusinessError) => {
267    if (!err) {
268        console.info(`Set static subscriber state callback failed, err is null.`);
269        return;
270    }
271    if (err.code !== undefined && err.code != null) {
272        console.info(`Set static subscriber state callback failed, errCode: ${err.code}, errMes: ${err.message}`);
273        return;
274    }
275    console.info(`Set static subscriber state callback success`);
276});
277```
278
279## CommonEventManager.setStaticSubscriberState<sup>10+</sup>
280
281setStaticSubscriberState(enable: boolean): Promise\<void>;
282
283Enables or disables static subscription for the current application. This API uses a promise to return the result.
284
285**Model restriction**: This API can be used only in the stage model.
286
287**System capability**: SystemCapability.Notification.CommonEvent
288
289**System API**: This is a system API and cannot be called by third-party applications.
290
291**Parameters**
292
293| Name| Type  | Mandatory| Description                      |
294| ------ | ------ | ---- | -------------------------- |
295| enable  | boolean | Yes  | Whether static subscription is enabled.<br> **true**: enabled.<br>**false**: disabled.|
296
297**Return value**
298
299| Type          | Description                        |
300| -------------- | ---------------------------- |
301| Promise\<void> | Promise used to return the result.|
302
303**Error codes**
304
305For details about the error codes, see [Event Error Codes](./errorcode-CommonEventService.md).
306
307| ID| Error Message                           |
308| -------- | ----------------------------------- |
309| 1500007  | error sending message to Common Event Service.             |
310| 1500008  | Common Event Service does not complete initialization.     |
311
312**Example**
313
314
315```ts
316import Base from '@ohos.base';
317
318CommonEventManager.setStaticSubscriberState(false).then(() => {
319    console.info(`Set static subscriber state promise success`);
320}).catch ((err:Base.BusinessError) => {
321    console.info(`Set static subscriber state promise failed, errCode: ${err.code}, errMes: ${err.message}`);
322});
323```
324