1# @ohos.commonEventManager (公共事件模块)(系统应用)
2
3本模块提供了公共事件相关的能力,包括发布公共事件、订阅公共事件以及退订公共事件。
4
5> **说明:**
6>
7> 本模块首批接口从API version 9开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
8>
9> 当前界面仅包含本模块的系统接口,其他公开接口参见[CommonEventManager](./js-apis-commonEventManager.md)。
10
11## 导入模块
12
13```ts
14import { commonEventManager } from '@kit.BasicServicesKit';
15```
16
17## Support
18
19系统公共事件是指由系统服务或系统应用发布的事件,订阅这些系统公共事件需要特定的权限。发布或订阅这些事件需要使用如下链接中的枚举定义。
20
21全部系统公共事件枚举定义请参见[系统公共事件定义](./common_event/commonEventManager-definitions.md)。
22
23## commonEventManager.publishAsUser<sup>
24
25publishAsUser(event: string, userId: number, callback: AsyncCallback\<void>): void
26
27以回调的形式向指定用户发布公共事件。
28
29**系统能力:** SystemCapability.Notification.CommonEvent
30
31**系统API**:此接口为系统接口,三方应用不支持调用。
32
33**参数:**
34
35| 参数名     | 类型                 | 必填 | 说明                               |
36| -------- | -------------------- | ---- | ---------------------------------- |
37| event    | string               | 是   | 表示要发送的公共事件。详见[系统公共事件定义](./common_event/commonEventManager-definitions.md)。             |
38| userId   | number               | 是   | 表示指定向该用户ID发送此公共事件。 |
39| callback | AsyncCallback\<void> | 是   | 表示被指定的回调方法。             |
40
41**错误码:**
42
43以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[事件错误码](./errorcode-CommonEventService.md)。
44
45| 错误码ID | 错误信息                            |
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**示例:**
55
56```ts
57import { BusinessError } from '@kit.BasicServicesKit';
58
59// 发布公共事件回调
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//指定发送的用户
69let userId = 100;
70
71//发布公共事件
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
84以回调形式向指定用户发布公共事件并指定发布信息。
85
86**系统能力:** SystemCapability.Notification.CommonEvent
87
88**系统API**:此接口为系统接口,三方应用不支持调用。
89
90**参数:**
91
92| 参数名     | 类型                   | 必填 | 说明                   |
93| -------- | ---------------------- | ---- | ---------------------- |
94| event    | string                 | 是   | 表示要发布的公共事件。详见[系统公共事件定义](./common_event/commonEventManager-definitions.md)。  |
95| userId   | number | 是 | 表示指定向该用户ID发送此公共事件。 |
96| options  | [CommonEventPublishData](./js-apis-inner-commonEvent-commonEventPublishData.md) | 是   | 表示发布公共事件的属性。 |
97| callback | AsyncCallback\<void>   | 是   | 表示被指定的回调方法。  |
98
99**错误码:**
100
101以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[事件错误码](./errorcode-CommonEventService.md)。
102
103| 错误码ID | 错误信息                            |
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**示例:**
113
114```ts
115import { BusinessError } from '@kit.BasicServicesKit';
116
117// 公共事件相关信息
118let options:commonEventManager.CommonEventPublishData = {
119  code: 0,			 // 公共事件的初始代码
120  data: "initial data",// 公共事件的初始数据
121}
122// 发布公共事件回调
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// 指定发送的用户
131let userId = 100;
132// 发布公共事件
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
145以回调形式移除粘性公共事件。
146
147**系统能力:** SystemCapability.Notification.CommonEvent
148
149**需要权限**:  ohos.permission.COMMONEVENT_STICKY
150
151**系统API**:此接口为系统接口,三方应用不支持调用。
152
153**参数:**
154
155| 参数名   | 类型                 | 必填 | 说明                             |
156| -------- | -------------------- | ---- | -------------------------------- |
157| event    | string               | 是   | 表示被移除的粘性公共事件。详见[系统公共事件定义](./common_event/commonEventManager-definitions.md)。       |
158| callback | AsyncCallback\<void> | 是   | 表示移除粘性公共事件的回调方法。 |
159
160**错误码:**
161
162以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[事件错误码](./errorcode-CommonEventService.md)。
163
164| 错误码ID | 错误信息                            |
165| -------- | ----------------------------------- |
166| 201      | The application dose 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**示例:**
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
191以Promise形式移除粘性公共事件。
192
193**系统能力:** SystemCapability.Notification.CommonEvent
194
195**需要权限**:  ohos.permission.COMMONEVENT_STICKY
196
197**系统API**:此接口为系统接口,三方应用不支持调用。
198
199**参数:**
200
201| 参数名 | 类型   | 必填 | 说明                       |
202| ------ | ------ | ---- | -------------------------- |
203| event  | string | 是   | 表示被移除的粘性公共事件。详见[系统公共事件定义](./common_event/commonEventManager-definitions.md)。 |
204
205**返回值:**
206
207| 类型           | 说明                         |
208| -------------- | ---------------------------- |
209| Promise\<void> | 表示移除粘性公共事件的对象。 |
210
211**错误码:**
212
213以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[事件错误码](./errorcode-CommonEventService.md)。
214
215| 错误码ID | 错误信息                            |
216| -------- | ----------------------------------- |
217| 201      | The application dose 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**示例:**
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
240方法介绍:为当前应用设置静态订阅事件使能或去使能状态。使用callback异步回调。
241
242**模型约束**:此接口仅可在Stage模型下使用。
243
244**系统能力:** SystemCapability.Notification.CommonEvent
245
246**系统API**:此接口为系统接口,三方应用不支持调用。
247
248**参数:**
249
250| 参数名 | 类型   | 必填 | 说明                       |
251| ------ | ------ | ---- | -------------------------- |
252| enable  | boolean | 是   | 表示静态订阅事件使能状态。 true:使能 false:去使能。 |
253| callback  | AsyncCallback\<void> | 是   | 表示设置静态订阅事件使能状态的回调方法。 |
254
255**错误码:**
256
257以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[事件错误码](./errorcode-CommonEventService.md)。
258
259| 错误码ID | 错误信息                            |
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**示例:**
267
268```ts
269import { BusinessError } from '@kit.BasicServicesKit';
270
271commonEventManager.setStaticSubscriberState(true, (err: BusinessError) => {
272  if (err.code != 0) {
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
284方法介绍:为当前应用设置静态订阅事件使能或去使能状态。使用Promise异步回调。
285
286**模型约束**:此接口仅可在Stage模型下使用。
287
288**系统能力:** SystemCapability.Notification.CommonEvent
289
290**系统API**:此接口为系统接口,三方应用不支持调用。
291
292**参数:**
293
294| 参数名 | 类型   | 必填 | 说明                       |
295| ------ | ------ | ---- | -------------------------- |
296| enable  | boolean | 是   | 表示静态订阅事件使能状态。 true:使能 false:去使能。 |
297
298**返回值:**
299
300| 类型           | 说明                         |
301| -------------- | ---------------------------- |
302| Promise\<void> |  Promise对象。无返回结果的Promise对象。|
303
304**错误码:**
305
306以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[事件错误码](./errorcode-CommonEventService.md)。
307
308| 错误码ID | 错误信息                            |
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**示例:**
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
332为当前应用设置静态订阅事件的使能状态,并且记录事件名称。使用Promise异步回调。
333
334**模型约束**:此接口仅可在Stage模型下使用。
335
336**系统能力**:SystemCapability.Notification.CommonEvent
337
338**系统接口**:此接口为系统接口。
339
340**参数:**
341
342| 参数名 | 类型          | 必填 | 说明                                                 |
343| ------ | ------------- | ---- | ---------------------------------------------------- |
344| enable | boolean       | 是   | 表示静态订阅事件使能状态。 true:使能 false:去使能。|
345| events | Array\<string> | 否   | 表示记录事件名称。                                   |
346
347**返回值:**
348
349| 类型           | 说明                                 |
350| -------------- | ------------------------------------ |
351| Promise\<void> | Promise对象。无返回结果的Promise对象。 |
352
353**错误码:**
354
355以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[事件错误码](./errorcode-CommonEventService.md)。。
356
357| 错误码ID | 错误信息                                               |
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**示例:**
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