common-event.md 7.2 KB
Newer Older
E
ester.zhou 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
# Common Event Development
### Introduction
OpenHarmony provides a Common Event Service (CES) for applications to subscribe to, publish, and unsubscribe from common events.

Common events are classified into system common events and custom common events.

+ 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.

+ Custom common event: customized by applications to implement cross-application event communication.

Each 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.

## Common Event Subscription Development

### When to Use
16
You 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).
E
ester.zhou 已提交
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45

### Available APIs
| API                                                                                         | Description|
| ---------------------------------------------------------------------------------------------- | ----------- |
| commonEvent.createSubscriber(subscribeInfo: CommonEventSubscribeInfo, callback: AsyncCallback) | Creates a subscriber. This API uses a callback to return the result.|
| commonEvent.createSubscriber(subscribeInfo: CommonEventSubscribeInfo)                          | Creates a subscriber. This API uses a promise to return the result. |
| commonEvent.subscribe(subscriber: CommonEventSubscriber, callback: AsyncCallback)              | Subscribes to common events.|

### How to Develop
1. Import the **commonEvent** module.

```javascript
import commonEvent from '@ohos.commonEvent';
```

2. Create a **subscribeInfo** object. For details about the data types and parameters of the object, see [CommonEventSubscribeInfo](../reference/apis/js-apis-commonEvent.md#commoneventsubscribeinfo).

```javascript
private subscriber = null	// Used to save the created subscriber object for subsequent subscription and unsubscription.

// Subscriber information
var subscribeInfo = {
    events: ["event"],
}
```

3. Create a subscriber object and save the returned object for subsequent operations such as subscription and unsubscription.

```javascript
E
ester.zhou 已提交
46
// Callback for subscriber creation.
E
ester.zhou 已提交
47 48 49 50 51 52 53 54 55 56 57 58 59 60
commonEvent.createSubscriber(subscribeInfo, (err, subscriber) => {
    if (err.code) {
        console.error("[CommonEvent]CreateSubscriberCallBack err=" + JSON.stringify(err))
    } else {
        console.log("[CommonEvent]CreateSubscriber")
        this.subscriber = subscriber
        this.result = "Create subscriber succeed"
    }
})
```

4. 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).

```javascript
E
ester.zhou 已提交
61
// Callback for common event subscription.
E
ester.zhou 已提交
62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176
if (this.subscriber != null) {
    commonEvent.subscribe(this.subscriber, (err, data) => {
        if (err.code) {
            console.error("[CommonEvent]SubscribeCallBack err=" + JSON.stringify(err))
        } else {
            console.log("[CommonEvent]SubscribeCallBack data=" + JSON.stringify(data))
            this.result = "receive, event = " + data.event + ", data = " + data.data + ", code = " + data.code
        }
    })
    this.result = "Subscribe succeed"
} else {
    prompt.showToast({ message: "Need create subscriber" })
}
```

## Public Event Publishing Development

### When to Use
You can use the **publish** APIs to publish a custom common event, which can carry data for subscribers to parse and process.

### Available APIs
| API                             | Description|
| ---------------------------------- | ------ |
| commonEvent.publish(event: string, callback: AsyncCallback) | Publishes a common event.|
| commonEvent.publish(event: string, options: CommonEventPublishData, callback: AsyncCallback) | Publishes a common event with given attributes.|

### How to Develop
#### Development for Publishing a Common Event
1. Import the **commonEvent** module.

```javascript
import commonEvent from '@ohos.commonEvent';
```

2. Pass in the common event name and callback, and publish the event.

```javascript
// Publish a common event.
commonEvent.publish("event", (err) => {
	if (err.code) {
		console.error("[CommonEvent]PublishCallBack err=" + JSON.stringify(err))
	} else {
		console.info("[CommonEvent]Publish1")
	}
})
```

#### Development for Publishing a Common Event with Given Attributes
1. Import the **commonEvent** module.

```javascript
import commonEvent from '@ohos.commonEvent'
```

2. 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).

```javascript
// Attributes of a common event.
var options = {
	code: 1,			 // Result code of the common event
	data: "initial data";// Result data of the common event
}
```

3. Pass in the common event name, attributes of the common event, and callback, and publish the event.

```javascript
// Publish a common event.
commonEvent.publish("event", options, (err) => {
	if (err.code) {
		console.error("[CommonEvent]PublishCallBack err=" + JSON.stringify(err))
	} else {
		console.info("[CommonEvent]Publish2")
	}
})
```

## Common Event Unsubscription Development

### When to Use
You can use the **unsubscribe** API to unsubscribe from a common event.

### Available APIs
| API                             | Description|
| ---------------------------------- | ------ |
| commonEvent.unsubscribe(subscriber: CommonEventSubscriber, callback?: AsyncCallback) | Unsubscribes from a common event.|

### How to Develop
1. Import the **commonEvent** module.

```javascript
import commonEvent from '@ohos.commonEvent';
```

2. Subscribe to a common event by following instructions in [Common Event Subscription Development](#Common-Event-Subscription-Development).
3. Invoke the **unsubscribe** API in **CommonEvent** to unsubscribe from the common event.

```javascript
if (this.subscriber != null) {
    commonEvent.unsubscribe(this.subscriber, (err) => {
        if (err.code) {
            console.error("[CommonEvent]UnsubscribeCallBack err=" + JSON.stringify(err))
        } else {
            console.log("[CommonEvent]Unsubscribe")
            this.subscriber = null
            this.result = "Unsubscribe succeed"
        }
    })
}
```

## Development Example

The following sample is provided to help you better understand how to use the common event functionality:

E
ester.zhou 已提交
177
- [CommonEvent](https://gitee.com/openharmony/app_samples/tree/master/ability/CommonEvent)
E
ester.zhou 已提交
178 179

This sample shows how to use **CommonEvent** APIs in Extended TypeScript (eTS) to create subscribers and subscribe to, publish, and unsubscribe from common events.