• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Common Event Development
2### Introduction
3OpenHarmony provides a Common Event Service (CES) for applications to subscribe to, publish, and unsubscribe from common events.
4
5Common events are classified into system common events and custom common events.
6
7+ System common events: The system sends an event based on system policies to the apps that have subscribed to this event when it occurs. This type of event is typically system events published by key system services, such as HAP installation, update, and uninstallation.
8
9+ Custom common event: customized by applications to implement cross-application event communication.
10
11Each application can subscribe to common events as required. After your application subscribes to a common event, the system sends it to your application every time the event is published. Such an event may be published by the system, other applications, or your own application.
12
13## Common Event Subscription Development
14
15### When to Use
16You can create a subscriber object to subscribe to a common event to obtain the parameters passed in the event. Certain system common events require specific permissions to subscribe to. For details, see [Required Permissions](../reference/apis/js-apis-commonEvent.md#required-permissions).
17
18### Available APIs
19| API                                                                                         | Description|
20| ---------------------------------------------------------------------------------------------- | ----------- |
21| commonEvent.createSubscriber(subscribeInfo: CommonEventSubscribeInfo, callback: AsyncCallback) | Creates a subscriber. This API uses a callback to return the result.|
22| commonEvent.createSubscriber(subscribeInfo: CommonEventSubscribeInfo)                          | Creates a subscriber. This API uses a promise to return the result. |
23| commonEvent.subscribe(subscriber: CommonEventSubscriber, callback: AsyncCallback)              | Subscribes to common events.|
24
25### How to Develop
261. Import the **commonEvent** module.
27
28```js
29import commonEvent from '@ohos.commonEvent';
30```
31
322. Create a **subscribeInfo** object. For details about the data types and parameters of the object, see [CommonEventSubscribeInfo](../reference/apis/js-apis-commonEvent.md#commoneventsubscribeinfo).
33
34```js
35private subscriber = null	// Used to save the created subscriber object for subsequent subscription and unsubscription.
36
37// Subscriber information
38var subscribeInfo = {
39    events: ["event"],
40}
41```
42
433. Create a subscriber object and save the returned object for subsequent operations such as subscription and unsubscription.
44
45```js
46// Callback for subscriber creation.
47commonEvent.createSubscriber(subscribeInfo, (err, subscriber) => {
48    if (err.code) {
49        console.error("[CommonEvent]CreateSubscriberCallBack err=" + JSON.stringify(err))
50    } else {
51        console.log("[CommonEvent]CreateSubscriber")
52        this.subscriber = subscriber
53        this.result = "Create subscriber succeed"
54    }
55})
56```
57
584. Create a subscription callback, which is triggered when an event is received. The data returned by the subscription callback contains information such as the common event name and data carried by the publisher. For details about the data types and parameters of the common event data, see [CommonEventData](../reference/apis/js-apis-commonEvent.md#commoneventdata).
59
60```js
61// Callback for common event subscription.
62if (this.subscriber != null) {
63    commonEvent.subscribe(this.subscriber, (err, data) => {
64        if (err.code) {
65            console.error("[CommonEvent]SubscribeCallBack err=" + JSON.stringify(err))
66        } else {
67            console.log("[CommonEvent]SubscribeCallBack data=" + JSON.stringify(data))
68            this.result = "receive, event = " + data.event + ", data = " + data.data + ", code = " + data.code
69        }
70    })
71    this.result = "Subscribe succeed"
72} else {
73    prompt.showToast({ message: "Need create subscriber" })
74}
75```
76
77## Common Event Publishing Development
78
79### When to Use
80You can use the **publish** APIs to publish a custom common event, which can carry data for subscribers to parse and process.
81
82### Available APIs
83| API                             | Description|
84| ---------------------------------- | ------ |
85| commonEvent.publish(event: string, callback: AsyncCallback) | Publishes a common event.|
86| commonEvent.publish(event: string, options: CommonEventPublishData, callback: AsyncCallback) | Publishes a common event with given attributes.|
87
88### How to Develop
89#### Development for Publishing a Common Event
901. Import the **commonEvent** module.
91
92```js
93import commonEvent from '@ohos.commonEvent';
94```
95
962. Pass in the common event name and callback, and publish the event.
97
98```js
99// Publish a common event.
100commonEvent.publish("event", (err) => {
101	if (err.code) {
102		console.error("[CommonEvent]PublishCallBack err=" + JSON.stringify(err))
103	} else {
104		console.info("[CommonEvent]Publish1")
105	}
106})
107```
108
109#### Development for Publishing a Common Event with Given Attributes
1101. Import the **commonEvent** module.
111
112```js
113import commonEvent from '@ohos.commonEvent'
114```
115
1162. Define attributes of the common event to publish. For details about the data types and parameters in the data to publish, see [CommonEventPublishData](../reference/apis/js-apis-commonEvent.md#commoneventpublishdata).
117
118```js
119// Attributes of a common event.
120var options = {
121	code: 1,			 // Result code of the common event
122	data: "initial data";// Result data of the common event
123}
124```
125
1263. Pass in the common event name, attributes of the common event, and callback, and publish the event.
127
128```js
129// Publish a common event.
130commonEvent.publish("event", options, (err) => {
131	if (err.code) {
132		console.error("[CommonEvent]PublishCallBack err=" + JSON.stringify(err))
133	} else {
134		console.info("[CommonEvent]Publish2")
135	}
136})
137```
138
139## Common Event Unsubscription Development
140
141### When to Use
142You can use the **unsubscribe** API to unsubscribe from a common event.
143
144### Available APIs
145| API                             | Description|
146| ---------------------------------- | ------ |
147| commonEvent.unsubscribe(subscriber: CommonEventSubscriber, callback?: AsyncCallback) | Unsubscribes from a common event.|
148
149### How to Develop
1501. Import the **commonEvent** module.
151
152```js
153import commonEvent from '@ohos.commonEvent';
154```
155
1562. Subscribe to a common event by following instructions in [Common Event Subscription Development](#Common-Event-Subscription-Development).
1573. Invoke the **unsubscribe** API in **CommonEvent** to unsubscribe from the common event.
158
159```js
160if (this.subscriber != null) {
161    commonEvent.unsubscribe(this.subscriber, (err) => {
162        if (err.code) {
163            console.error("[CommonEvent]UnsubscribeCallBack err=" + JSON.stringify(err))
164        } else {
165            console.log("[CommonEvent]Unsubscribe")
166            this.subscriber = null
167            this.result = "Unsubscribe succeed"
168        }
169    })
170}
171```
172