未验证 提交 4ff45c20 编写于 作者: O openharmony_ci 提交者: Gitee

!2850 2045 处理完成:新增 notification 文件夹

Merge pull request !2850 from ester.zhou/TR-2045-1
# Common Event and Notification
[Common Event and Notification Overview](notification-brief.md)
### Common Event
* [Common Event Development](common-event.md)
### Notification
* [Notification Development](notification.md)
### Debugging Tools
* [Debugging Assistant Usage](assistant-guidelines.md)
# Debugging Assistant Usage
The common event and notification module provides debugging tools to facilitate your application development. With these tools, you can view common event and notification information, publish common events, and more. These tools have been integrated with the system. You can run related commands directly in the shell.
### cem Debugging Assistant
##### publish
* Functionality
Publishes a common event.
* Usage
`cem publish [<options>]`
The table below describes the available options.
| Option | Description |
| ------------ | ------------------------------------------ |
| -e/--event | Indicates the name of the common event to publish. Mandatory. |
| -s/--sticky | Indicates that the common event to publish is sticky. Optional. By default, non-sticky events are published.|
| -o/--ordered | Indicates that the common event to publish is ordered. Optional. By default, non-ordered events are published. |
| -c/--code | Indicates the result code of the common event. Optional. |
| -d/--data | Indicates the data carried in the common event. Optional. |
| -h/--help | Indicates the help Information |
* Example
`cem publish --event "testevent"`
Publish a common event named **testevent**.
![cem-publish-event](figures/cem-publish-event.png)
`cem publish -e "testevent" -s -o -c 100 -d "this is data" `
Publish a sticky, ordered common event named **testevent**. The result code of the event is **100** and the data carried is **this is data**.
![cem-publish-all](figures/cem-publish-all.png)
##### dump
* Functionality
Displays information about common events.
* Usage
`cem dump [<options>]`
The table below describes the available options.
| Option | Description |
| ---------- | -------------------------------------------- |
| -a/--all | Displays information about all common events that have been sent since system startup.|
| -e/--event | Displays information about a specific event. |
| -h/--help | Displays the help information. |
* Example
`cem dump -e "testevent"`
​ Display information about the common event testevent.
​ ![cem-dump-e](figures/cem-dump-e.png)
##### help
* Functionality
Displays the help information.
* Usage
`cem help`
* Example
![cem-help](figures/cem-help.png)
### anm Debugging Assistant
##### dump
* Functionality
Displays information about notifications.
* Usage
`anm dump [<options>]`
The table below describes the available options.
| Option | Description |
| ---------------- | ---------------------------------------- |
| -A/--active | Displays information about all active notifications. |
| -R/--recent | Displays information about the recent notifications. |
| -D/--distributed | Displays information about distributed notifications from other devices. |
| --setRecentCount | Indicates the number of the cached recent notifications to be displayed. Optional.|
| -h/--help | Displays the help information. |
* Example
`anm dump -A`
Displays information about all active notifications.
![anm-dump-A](figures/anm-dump-A.png)
`anm dump --setRecentCount 10`
Set the number of the cached recent notifications to be displayed to 10.
##### help
* Functionality
Displays the help information.
* Usage
`anm help`
* Example
![anm-help](figures/anm-help.png)
# 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
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).
### 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
// Callback for subscriber creation
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
// Callback for common event subscription
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:
- [EtsCommonEvent](https://gitee.com/openharmony/app_samples/tree/master/ability/EtsCommonEvent)
This sample shows how to use **CommonEvent** APIs in Extended TypeScript (eTS) to create subscribers and subscribe to, publish, and unsubscribe from common events.
# Common Event and Notification Overview
The common event and notification module enables applications to publish messages to other applications, and receive messages from the system or other applications. These messages can be news push messages, advertisement notifications, or warning information.
Common Event Service (CES) enables applications to publish, subscribe to, and unsubscribe from common events. Based on the sender type, common events are classified into system common events and custom common events.
![ces](figures/ces.png)
- System common event: sent by the system based on system policies to the applications that have subscribed to the event. This type of event includes the screen-on/off events that the users are aware of and the system events published by key system services, such as USB device attachment or detachment, network connection, and system update events.
- Custom common event: customized by applications to be received by specific subscribers. This type of event is usually related to the service logic of the sender applications.
The Advanced Notification Service (ANS) enables applications to publish notifications. Below are some typical use cases for publishing notifications:
- Display received SMS messages and instant messages.
- Display push messages of applications, such as advertisements, version updates, and news notifications.
- Display ongoing events, such as music playback, navigation information, and download progress.
Notifications are displayed in the notification panel. Uses can delete a notification or click the notification to trigger predefined actions.
![ans](figures/ans.png)
# Notification Development
## When to Use
OpenHarmony uses the Advanced Notification Service (ANS) to manage notifications, with support for various notification types, including text, long text, multi-text, image, social, and media. All system services and applications can send notifications through the notification API. Users can view all notifications on the system UI.
Below are some typical use cases for notifications:
- Display received SMS messages and instant messages.
- Display push messages of applications, such as advertisements and version updates.
- Display ongoing events, such as navigation information and download progress.
## Notification Service Process
The notification service process involves the ANS subsystem, notification sender, and notification subscriber.
A notification is generated by the notification sender and sent to the ANS through inter-process communication (IPC). The ANS then distributes the notification to the notification subscriber.
System applications also support notification-related configuration options, such as switches. The system configuration initiates a configuration request and sends the request to the ANS for storage in the memory and database.
![1648113187545](figures/notification.png)
## Available APIs
Certain APIs can be invoked only by system applications that have been granted the **SystemCapability.Notification.Notification** permission. The APIs use either a callback or promise to return the result. The tables below list the APIs that use a callback, which provide same functions as their counterparts that use a promise. For details about the APIs, see the [API document](https://gitee.com/openharmony/docs/blob/master/en/application-dev/reference/apis/js-apis-notification.md).
**Table 1** APIs for notification enabling
| API | Description |
| ------------------------------------------------------------ | ---------------- |
| isNotificationEnabled(bundle: BundleOption, callback: AsyncCallback<boolean>): void | Checks whether notification is enabled.|
| enableNotification(bundle: BundleOption, enable: boolean, callback: AsyncCallback<void>): void | Sets whether to enable notification. |
If the notification function of an application is disabled, it cannot send notifications.
**Table 2** APIs for notification subscription
| API | Description |
| ------------------------------------------------------------ | ---------------- |
| subscribe(subscriber: NotificationSubscriber, info: NotificationSubscribeInfo, callback: AsyncCallback<void>): void | Subscribes to a notification with the subscription information specified.|
| subscribe(subscriber: NotificationSubscriber, callback: AsyncCallback<void>): void | Subscribes to all notifications. |
| unsubscribe(subscriber: NotificationSubscriber, callback: AsyncCallback<void>): void | Unsubscribes from a notification. |
The subscription APIs support subscription to all notifications or notifications from specific applications.
**Table 3** Notification subscription callbacks
| API | Description |
| ------------------------------------------------ | ---------------- |
| onConsume?:(data: SubscribeCallbackData) => void | Callback for receiving notifications. |
| onCancel?:(data: SubscribeCallbackData) => void | Callback for canceling notifications. |
| onUpdate?:(data: NotificationSortingMap) => void | Callback for notification sorting updates.|
| onConnect?:() => void; | Callback for subscription. |
| onDisconnect?:() => void; | Callback for unsubscription. |
**Table 4** APIs for notification sending
| API | Description |
| ------------------------------------------------------------ | ------------------------ |
| publish(request: NotificationRequest, callback: AsyncCallback<void>): void | Publishes a notification. |
| publish(request: NotificationRequest, userId: number, callback: AsyncCallback<void>): void | Publishes a notification to the specified user. |
| cancel(id: number, label: string, callback: AsyncCallback<void>): void | Cancels a specified notification. |
| cancelAll(callback: AsyncCallback<void>): void; | Cancels all notifications published by the application.|
The **publish** API that carries **userId** can be used to publish notifications to subscribers of a specified user.
## Development Guidelines
The notification development process generally involves three aspects: subscribing to notifications, enabling the notification feature, and publishing notifications.
### Modules to Import
```js
import Notification from '@ohos.notification';
```
### Subscribing to Notifications
The notification recipient preferentially initiates a notification subscription request to the notification subsystem.
```js
var subscriber = {
onConsume: function (data) {
let req = data.request;
console.info('===>onConsume callback req.id: ' + req.id);
},
onCancel: function (data) {
let req = data.request;
console.info('===>onCancel callback req.id: : ' + req.id);
},
onUpdate: function (data) {
console.info('===>onUpdate in test===>');
},
onConnect: function () {
console.info('===>onConnect in test===>');
},
onDisconnect: function () {
console.info('===>onDisConnect in test===>');
},
onDestroy: function () {
console.info('===>onDestroy in test===>');
},
};
Notification.subscribe(subscriber, (err, data) => { // This API uses an asynchronous callback to return the result.
if (err.code) {
console.error('===>failed to subscribe because ' + JSON.stringify(err));
return;
}
console.info('===>subscribeTest success : ' + JSON.stringify(data));
});
```
### Publishing Notifications
Before publishing a notification, check whether the notification feature is enabled for the respective application. By default, the feature is disabled for newly installed apps.
##### Enabling Notification
Check whether notification is enabled.
```js
var bundle = {
bundle: "bundleName1",
}
Notification.isNotificationEnabled(bundle).then((data) => {
console.info("===>isNotificationEnabled success===>");
});
```
If the check result is **false**, notification is disabled. In this case, enable it.
```js
var bundle = {
bundle: "bundleName1",
}
Notification.enableNotification(bundle, true, async(err) => {
console.log("===>enableNotification success===>");
});
```
##### Publishing Notifications
To publish a notification, create a **NotificationRequest** object and set attributes such as the notification type, title, and content. In the following examples, a normal text notification and a notification containing a **WantAgent** are being published.
Normal Text Notification
```js
// Create a NotificationRequest object.
var notificationRequest = {
id: 1,
content: {
contentType: notify.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT,
normal: {
title: "test_title",
text: "test_text",
additionalText: "test_additionalText"
}
}
}
// Publish the notification.
Notification.publish(notificationRequest) .then((data) => {
console.info('===>publish promise success req.id : ' + notificationRequest.id);
}).catch((err) => {
console.error('===>publish promise failed because ' + JSON.stringify(err));
});
```
Notification Containing WantAgent.
For details about how to use **WantAgent**, see [WantAgent Development](https://gitee.com/openharmony/docs/blob/master/en/application-dev/ability/wantagent.md).
- Create a **WantAgent** object.
```js
import wantAgent from '@ohos.wantAgent';
import { OperationType, Flags } from '@ohos.wantagent';
// WantAgentInfo object
var wantAgentInfo = {
wants: [
{
deviceId: 'deviceId',
bundleName: 'com.example.myapplication',
abilityName: 'com.example.myapplication.MainAbility',
action: 'REMINDER_EVENT_REMOVE_NOTIFICATION',
entities: ['entity1'],
type: 'MIMETYPE',
uri: 'key={true,true,false}',
parameters: { myKey0: 1111 },
}
],
operationType: OperationType.START_ABILITIES,
requestCode: 0,
wantAgentFlags:[Flags.UPDATE_PRESENT_FLAG]
}
// WantAgent object
var WantAgent;
// getWantAgent callback
function getWantAgentCallback(err, data) {
console.info("===>getWantAgentCallback===>");
if (err.code == 0) {
WantAgent = data;
} else {
console.info('----getWantAgent failed!----');
}
}
// Obtain the WantAgent object.
wantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback)
```
- Publish the notification.
```js
// Create a NotificationRequest object.
var notificationRequest = {
content: {
contentType: notify.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT,
normal: {
title: "AceApplication_Title",
text: "AceApplication_Text",
additionalText: "AceApplication_AdditionalText"
},
},
id: 1,
label: 'TEST',
wantAgent: WantAgent,
slotType: notify.SlotType.OTHER_TYPES,
deliveryTime: new Date().getTime()
}
// Publish the notification.
Notification.publish(notificationRequest) .then((data) => {
console.info('===>publish promise success req.id : ' + notificationRequest.id);
}).catch((err) => {
console.error('===>publish promise failed because ' + JSON.stringify(err));
});
```
- Cancel the notification.
An application can cancel a single notification or all notifications. An application can cancel only the notifications published by itself.
```js
// cancel callback
function cancelCallback(err) {
console.info("===>cancelCallback===>");
}
Notification.cancel(1, "label", cancelCallback)
```
## Development Example
The following sample is provided to help you better understand how to develop notification functions:
- notification
This sample shows how to use **Notification** APIs in Extended TypeScript (eTS) to subscribe to, unsubscribe from, publish, and cancel notifications as well as enable the notification feature and check whether the feature is enabled.
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册