1# @ohos.commonEventManager (Common Event) 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## Modules to Import 10 11```ts 12import { commonEventManager } from '@kit.BasicServicesKit'; 13``` 14 15## Support 16 17System common events refer to events released by system services or system applications. Subscribing to these common events requires specific permissions and values. For details, see [System Common Events](./common_event/commonEventManager-definitions.md). 18 19## commonEventManager.publish 20 21publish(event: string, callback: AsyncCallback\<void>): void 22 23Publishes a common event. This API uses an asynchronous callback to return the result. 24 25**Atomic service API**: This API can be used in atomic services since API version 11. 26 27**System capability**: SystemCapability.Notification.CommonEvent 28 29**Parameters** 30 31| Name | Type | Mandatory| Description | 32| -------- | -------------------- | ---- | ---------------------- | 33| event | string | Yes | Name of the common event to publish. For details, see [System Common Events](./common_event/commonEventManager-definitions.md).| 34| callback | AsyncCallback\<void> | Yes | Callback to execute after the event is published.| 35 36**Error codes** 37 38For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Event Error Codes](./errorcode-CommonEventService.md). 39 40| ID| Error Message | 41| -------- | ----------------------------------- | 42| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 43| 1500004 | A third-party application cannot send system common events. | 44| 1500007 | Failed to send the message to the common event service. | 45| 1500008 | Failed to initialize the common event service. | 46| 1500009 | Failed to obtain system parameters. | 47 48**Example** 49 50```ts 51import { BusinessError } from '@kit.BasicServicesKit'; 52 53// Callback for common event publication. 54function publishCB(err: BusinessError) { 55 if (err) { 56 console.error(`publish failed, code is ${err.code}, message is ${err.message}`); 57 } else { 58 console.info("publish success"); 59 } 60} 61// Publish a common event. 62try { 63 commonEventManager.publish("event", publishCB); 64} catch (error) { 65 let err: BusinessError = error as BusinessError; 66 console.error(`publish failed, code is ${err.code}, message is ${err.message}`); 67} 68``` 69 70## commonEventManager.publish 71 72publish(event: string, options: CommonEventPublishData, callback: AsyncCallback\<void>): void 73 74Publishes a common event. This API uses an asynchronous callback to return the result. 75 76**Atomic service API**: This API can be used in atomic services since API version 11. 77 78**System capability**: SystemCapability.Notification.CommonEvent 79 80**Parameters** 81 82| Name | Type | Mandatory| Description | 83| -------- | ---------------------- | ---- | ---------------------- | 84| event | string | Yes | Name of the common event to publish. For details, see [System Common Events](./common_event/commonEventManager-definitions.md). | 85| options | [CommonEventPublishData](./js-apis-inner-commonEvent-commonEventPublishData.md) | Yes | Attributes of the common event to publish.| 86| callback | syncCallback\<void> | Yes | Callback used to return the result. | 87 88**Error codes** 89 90For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Event Error Codes](./errorcode-CommonEventService.md). 91 92| ID| Error Message | 93| -------- | ----------------------------------- | 94| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 95| 1500004 | A third-party application cannot send system common events. | 96| 1500007 | Failed to send the message to the common event service. | 97| 1500008 | Failed to initialize the common event service. | 98| 1500009 | Failed to obtain system parameters. | 99 100**Example** 101 102```ts 103import { BusinessError } from '@kit.BasicServicesKit'; 104 105// Attributes of a common event. 106let options:commonEventManager.CommonEventPublishData = { 107 code: 0, // Result code of the common event. 108 data: "initial data",// Result data of the common event. 109 isOrdered: true // The common event is an ordered one. 110} 111// Callback for common event publication. 112function publishCB(err: BusinessError) { 113 if (err) { 114 console.error(`publish failed, code is ${err.code}, message is ${err.message}`); 115 } else { 116 console.info("publish success"); 117 } 118} 119// Publish a common event. 120try { 121 commonEventManager.publish("event", options, publishCB); 122} catch (error) { 123 let err: BusinessError = error as BusinessError; 124 console.error(`publish failed, code is ${err.code}, message is ${err.message}`); 125} 126``` 127 128## commonEventManager.createSubscriber 129 130createSubscriber(subscribeInfo: CommonEventSubscribeInfo, callback: AsyncCallback\<CommonEventSubscriber>): void 131 132Creates a subscriber. This API uses an asynchronous callback to return the result. 133 134**Atomic service API**: This API can be used in atomic services since API version 11. 135 136**System capability**: SystemCapability.Notification.CommonEvent 137 138**Parameters** 139 140| Name | Type | Mandatory| Description | 141| ------------- | ------------------------------------------------------------ | ---- | -------------------------- | 142| subscribeInfo | [CommonEventSubscribeInfo](./js-apis-inner-commonEvent-commonEventSubscribeInfo.md) | Yes | Subscriber information. | 143| callback | AsyncCallback\<[CommonEventSubscriber](./js-apis-inner-commonEvent-commonEventSubscriber.md)> | Yes | Callback used to return the result.| 144 145**Error codes** 146 147For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 148 149| ID| Error Message | 150| -------- | ----------------------------------- | 151| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 152 153**Example** 154 155```ts 156import { BusinessError } from '@kit.BasicServicesKit'; 157 158// Define a subscriber to save the created subscriber object for subsequent subscription and unsubscription. 159let subscriber:commonEventManager.CommonEventSubscriber; 160// Attributes of a subscriber. 161let subscribeInfo:commonEventManager.CommonEventSubscribeInfo = { 162 events: ["event"] 163}; 164// Callback for subscriber creation. 165function createCB(err: BusinessError, commonEventSubscriber:commonEventManager.CommonEventSubscriber) { 166 if(!err) { 167 console.info("createSubscriber success"); 168 subscriber = commonEventSubscriber; 169 } else { 170 console.error(`createSubscriber failed, code is ${err.code}, message is ${err.message}`); 171 } 172} 173// Create a subscriber. 174try { 175 commonEventManager.createSubscriber(subscribeInfo, createCB); 176} catch (error) { 177 let err: BusinessError = error as BusinessError; 178 console.error(`createSubscriber failed, code is ${err.code}, message is ${err.message}`); 179} 180``` 181 182## commonEventManager.createSubscriber 183 184createSubscriber(subscribeInfo: CommonEventSubscribeInfo): Promise\<CommonEventSubscriber> 185 186Creates a subscriber. This API uses a promise to return the result. 187 188**Atomic service API**: This API can be used in atomic services since API version 11. 189 190**System capability**: SystemCapability.Notification.CommonEvent 191 192**Parameters** 193 194| Name | Type | Mandatory| Description | 195| ------------- | ----------------------------------------------------- | ---- | -------------- | 196| subscribeInfo | [CommonEventSubscribeInfo](./js-apis-inner-commonEvent-commonEventSubscribeInfo.md) | Yes | Subscriber information.| 197 198**Return value** 199| Type | Description | 200| --------------------------------------------------------- | ---------------- | 201| Promise\<[CommonEventSubscriber](./js-apis-inner-commonEvent-commonEventSubscriber.md)> | Promise used to return the result.| 202 203**Error codes** 204 205For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 206 207| ID| Error Message | 208| -------- | ----------------------------------- | 209| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 210 211**Example** 212 213```ts 214import { BusinessError } from '@kit.BasicServicesKit'; 215 216// Define a subscriber to save the created subscriber object for subsequent subscription and unsubscription. 217let subscriber:commonEventManager.CommonEventSubscriber; 218// Attributes of a subscriber. 219let subscribeInfo:commonEventManager.CommonEventSubscribeInfo = { 220 events: ["event"] 221}; 222// Create a subscriber. 223commonEventManager.createSubscriber(subscribeInfo).then((commonEventSubscriber:commonEventManager.CommonEventSubscriber) => { 224 console.info("createSubscriber success"); 225 subscriber = commonEventSubscriber; 226}).catch((err: BusinessError) => { 227 console.error(`createSubscriber failed, code is ${err.code}, message is ${err.message}`); 228}); 229``` 230 231## commonEventManager.createSubscriberSync<sup>10+</sup> 232 233createSubscriberSync(subscribeInfo: CommonEventSubscribeInfo): CommonEventSubscriber 234 235Creates a subscriber. The API returns the result synchronously. 236 237**Atomic service API**: This API can be used in atomic services since API version 11. 238 239**System capability**: SystemCapability.Notification.CommonEvent 240 241**Parameters** 242 243| Name | Type | Mandatory| Description | 244| ------------- | ----------------------------------------------------- | ---- | -------------- | 245| subscribeInfo | [CommonEventSubscribeInfo](./js-apis-inner-commonEvent-commonEventSubscribeInfo.md) | Yes | Subscriber information.| 246 247**Return value** 248| Type | Description | 249| --------------------------------------------------------- | ---------------- | 250| [CommonEventSubscriber](./js-apis-inner-commonEvent-commonEventSubscriber.md) | Promise used to return the subscriber object.| 251 252**Error codes** 253 254For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 255 256| ID| Error Message | 257| -------- | ----------------------------------- | 258| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 259 260**Example** 261 262```ts 263import { BusinessError } from '@kit.BasicServicesKit'; 264 265// Define a subscriber to save the created subscriber object for subsequent subscription and unsubscription. 266let subscriber: commonEventManager.CommonEventSubscriber; 267// Attributes of a subscriber. 268let subscribeInfo: commonEventManager.CommonEventSubscribeInfo = { 269 events: ["event"] 270}; 271// Create a subscriber. 272try { 273 subscriber = commonEventManager.createSubscriberSync(subscribeInfo); 274} catch (error) { 275 let err: BusinessError = error as BusinessError; 276 console.error(`createSubscriberSync failed, code is ${err.code}, message is ${err.message}`); 277} 278``` 279 280## commonEventManager.subscribe 281 282subscribe(subscriber: CommonEventSubscriber, callback: AsyncCallback\<CommonEventData>): void 283 284Subscribes to a common event. This API uses an asynchronous callback to return the result. 285 286**Atomic service API**: This API can be used in atomic services since API version 11. 287 288**System capability**: SystemCapability.Notification.CommonEvent 289 290**Parameters** 291 292| Name | Type | Mandatory| Description | 293| ---------- | ---------------------------------------------------- | ---- | -------------------------------- | 294| subscriber | [CommonEventSubscriber](./js-apis-inner-commonEvent-commonEventSubscriber.md) | Yes | Subscriber object. | 295| callback | AsyncCallback\<[CommonEventData](./js-apis-inner-commonEvent-commonEventData.md)> | Yes | Callback used to return the result.| 296 297**Error codes** 298 299For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Event Error Codes](./errorcode-CommonEventService.md). 300 301| ID| Error Message | 302| -------- | ----------------------------------- | 303| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 304| 801 | capability not supported. | 305| 1500007 | Failed to send the message to the common event service. | 306| 1500008 | Failed to initialize the common event service. | 307 308**Example** 309 310```ts 311import { BusinessError } from '@kit.BasicServicesKit'; 312 313// Define a subscriber to save the created subscriber object for subsequent subscription and unsubscription. 314let subscriber:commonEventManager.CommonEventSubscriber; 315// Attributes of a subscriber. 316let subscribeInfo:commonEventManager.CommonEventSubscribeInfo = { 317 events: ["event"] 318}; 319// Callback for common event subscription. 320function SubscribeCB(err: BusinessError, data:commonEventManager.CommonEventData) { 321 if (err) { 322 console.error(`subscribe failed, code is ${err.code}, message is ${err.message}`); 323 } else { 324 console.info("subscribe success, Consume callback " + JSON.stringify(data)); 325 } 326} 327// Callback for subscriber creation. 328function createCB(err: BusinessError, commonEventSubscriber:commonEventManager.CommonEventSubscriber) { 329 if(!err) { 330 console.info("createSubscriber success"); 331 subscriber = commonEventSubscriber; 332 // Subscribe to a common event. 333 try { 334 commonEventManager.subscribe(subscriber, SubscribeCB); 335 } catch (error) { 336 let err: BusinessError = error as BusinessError; 337 console.error(`subscribe failed, code is ${err.code}, message is ${err.message}`); 338 } 339 } else { 340 console.error(`createSubscriber failed, code is ${err.code}, message is ${err.message}`); 341 } 342} 343// Create a subscriber. 344try { 345 commonEventManager.createSubscriber(subscribeInfo, createCB); 346} catch (error) { 347 let err: BusinessError = error as BusinessError; 348 console.error(`createSubscriber failed, code is ${err.code}, message is ${err.message}`); 349} 350``` 351 352## commonEventManager.unsubscribe 353 354unsubscribe(subscriber: CommonEventSubscriber, callback?: AsyncCallback\<void>): void 355 356Unsubscribes from a common event. This API uses an asynchronous callback to return the result. 357 358**Atomic service API**: This API can be used in atomic services since API version 11. 359 360**System capability**: SystemCapability.Notification.CommonEvent 361 362**Parameters** 363 364| Name | Type | Mandatory| Description | 365| ---------- | ----------------------------------------------- | ---- | ------------------------ | 366| subscriber | [CommonEventSubscriber](./js-apis-inner-commonEvent-commonEventSubscriber.md) | Yes | Subscriber object. | 367| callback | AsyncCallback\<void> | No | Callback used to return the result.| 368 369**Error codes** 370 371For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Event Error Codes](./errorcode-CommonEventService.md). 372 373| ID| Error Message | 374| -------- | ----------------------------------- | 375| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 376| 801 | capability not supported. | 377| 1500007 | Failed to send the message to the common event service. | 378| 1500008 | Failed to initialize the common event service. | 379 380**Example** 381 382```ts 383import { BusinessError } from '@kit.BasicServicesKit'; 384 385// Define a subscriber to save the created subscriber object for subsequent subscription and unsubscription. 386let subscriber:commonEventManager.CommonEventSubscriber; 387// Attributes of a subscriber. 388let subscribeInfo:commonEventManager.CommonEventSubscribeInfo = { 389 events: ["event"] 390}; 391// Callback for common event subscription. 392function subscribeCB(err: BusinessError, data:commonEventManager.CommonEventData) { 393 if (err) { 394 console.error(`subscribe failed, code is ${err.code}, message is ${err.message}`); 395 } else { 396 console.info("subscribe success, Consume callback " + JSON.stringify(data)); 397 } 398} 399// Callback for subscriber creation. 400function createCB(err: BusinessError, commonEventSubscriber:commonEventManager.CommonEventSubscriber) { 401 if (err) { 402 console.error(`createSubscriber failed, code is ${err.code}, message is ${err.message}`); 403 } else { 404 console.info("createSubscriber success"); 405 subscriber = commonEventSubscriber; 406 // Subscribe to a common event. 407 try { 408 commonEventManager.subscribe(subscriber, subscribeCB); 409 } catch (error) { 410 let err: BusinessError = error as BusinessError; 411 console.error(`subscribe failed, code is ${err.code}, message is ${err.message}`); 412 } 413 } 414} 415// Callback for common event unsubscription. 416function unsubscribeCB(err: BusinessError) { 417 if (err) { 418 console.error(`unsubscribe failed, code is ${err.code}, message is ${err.message}`); 419 } else { 420 console.info("unsubscribe success"); 421 } 422} 423// Create a subscriber. 424try { 425 commonEventManager.createSubscriber(subscribeInfo, createCB); 426} catch (error) { 427 let err: BusinessError = error as BusinessError; 428 console.error(`createSubscriber failed, code is ${err.code}, message is ${err.message}`); 429} 430 431// Unsubscribe from the common event. 432// Wait until execution of the asynchronous API subscribe is completed. Add setTimeout when necessary. 433setTimeout(() => { 434 try { 435 commonEventManager.unsubscribe(subscriber, unsubscribeCB); 436 } catch (error) { 437 let err: BusinessError = error as BusinessError; 438 console.error(`unsubscribe failed, code is ${err.code}, message is ${err.message}`); 439 } 440}, 500); 441``` 442