You need to sign in or sign up before continuing.
notification-guidelines.md 9.6 KB
Newer Older
E
ester.zhou 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 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 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 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


# 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

E
ester.zhou 已提交
134 135
##### Enabling Notification

E
ester.zhou 已提交
136
Before publishing a notification, check whether the notification feature is enabled for your application. By default, the feature is disabled. The application calls **Notification.requestEnableNotification** to prompt the user to enable the feature.
E
ester.zhou 已提交
137 138 139 140 141 142 143 144 145 146

```js
Notification.requestEnableNotification() .then((data) => {
	console.info('===>requestEnableNotification success');
}).catch((err) => {
	console.error('===>requestEnableNotification failed because ' + JSON.stringify(err));
});
```


E
ester.zhou 已提交
147 148 149 150 151

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

E
ester.zhou 已提交
152
Normal text notification:
E
ester.zhou 已提交
153 154 155 156 157 158

```js
// Create a NotificationRequest object.
var notificationRequest = {
  	id: 1,
  	content: {
E
ester.zhou 已提交
159
  		contentType: Notification.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT,
E
ester.zhou 已提交
160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177
  		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));
});
```



E
ester.zhou 已提交
178
Notification containing **WantAgent**:
E
ester.zhou 已提交
179 180 181 182 183 184 185 186 187 188

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';

// WantAgentInfo object
var wantAgentInfo = {
E
ester.zhou 已提交
189 190 191 192 193 194 195 196 197
  wants: [
    {
      bundleName: 'ohos.samples.eTSNotification',
      abilityName: 'ohos.samples.eTSNotification.MainAbility',
    }
  ],
  operationType: wantAgent.OperationType.START_ABILITY,
  requestCode: 0,
  wantAgentFlags:[wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG]
E
ester.zhou 已提交
198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216
}

// 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)
```

E
ester.zhou 已提交
217
- Publish the notification.
E
ester.zhou 已提交
218 219 220 221 222

```js
// Create a NotificationRequest object.
var notificationRequest = {
  content: {
E
ester.zhou 已提交
223
    contentType: Notification.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT,
E
ester.zhou 已提交
224 225 226 227 228 229 230 231 232
    normal: {
      title: "AceApplication_Title",
      text: "AceApplication_Text",
      additionalText: "AceApplication_AdditionalText"
    },
  },
  id: 1,
  label: 'TEST',
  wantAgent: WantAgent,
E
ester.zhou 已提交
233
  slotType: Notification.SlotType.OTHER_TYPES,
E
ester.zhou 已提交
234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260
  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)
```


E
ester.zhou 已提交
261 262 263 264
## Samples

The following sample is provided to help you better understand how to develop notification functions:

E
ester.zhou 已提交
265
[`Notification`: EtsNotification (API 8)](https://gitee.com/openharmony/app_samples/tree/master/common/Notification)