1 2 3# Notification Development 4 5## When to Use 6 7OpenHarmony 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. 8 9Below are some typical use cases for notifications: 10 11- Display received SMS messages and instant messages. 12- Display push messages of applications, such as advertisements and version updates. 13- Display ongoing events, such as navigation information and download progress. 14 15 16 17## Notification Service Process 18 19The notification service process involves the ANS subsystem, notification sender, and notification subscriber. 20 21A 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. 22 23System 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. 24 25 26 27 28 29## Available APIs 30 31Certain 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). 32 33**Table 1** APIs for notification enabling 34 35| API | Description | 36| ------------------------------------------------------------ | ---------------- | 37| isNotificationEnabled(bundle: BundleOption, callback: AsyncCallback\<boolean>): void | Checks whether notification is enabled.| 38| enableNotification(bundle: BundleOption, enable: boolean, callback: AsyncCallback\<void>): void | Sets whether to enable notification. | 39 40If the notification function of an application is disabled, it cannot send notifications. 41 42 43 44**Table 2** APIs for notification subscription 45 46| API | Description | 47| ------------------------------------------------------------ | ---------------- | 48| subscribe(subscriber: NotificationSubscriber, info: NotificationSubscribeInfo, callback: AsyncCallback\<void>): void | Subscribes to a notification with the subscription information specified.| 49| subscribe(subscriber: NotificationSubscriber, callback: AsyncCallback\<void>): void | Subscribes to all notifications. | 50| unsubscribe(subscriber: NotificationSubscriber, callback: AsyncCallback\<void>): void | Unsubscribes from a notification. | 51 52The subscription APIs support subscription to all notifications or notifications from specific applications. 53 54 55 56**Table 3** Notification subscription callbacks 57 58| API | Description | 59| ------------------------------------------------ | ---------------- | 60| onConsume?:(data: SubscribeCallbackData) => void | Callback for receiving notifications. | 61| onCancel?:(data: SubscribeCallbackData) => void | Callback for canceling notifications. | 62| onUpdate?:(data: NotificationSortingMap) => void | Callback for notification sorting updates.| 63| onConnect?:() => void; | Callback for subscription. | 64| onDisconnect?:() => void; | Callback for unsubscription. | 65 66 67 68**Table 4** APIs for notification sending 69 70| API | Description | 71| ------------------------------------------------------------ | ------------------------ | 72| publish(request: NotificationRequest, callback: AsyncCallback\<void>): void | Publishes a notification. | 73| publish(request: NotificationRequest, userId: number, callback: AsyncCallback\<void>): void | Publishes a notification to the specified user. | 74| cancel(id: number, label: string, callback: AsyncCallback\<void>): void | Cancels a specified notification. | 75| cancelAll(callback: AsyncCallback\<void>): void; | Cancels all notifications published by the application.| 76 77The **publish** API that carries **userId** can be used to publish notifications to subscribers of a specified user. 78 79 80 81## Development Guidelines 82 83The notification development process generally involves three aspects: subscribing to notifications, enabling the notification feature, and publishing notifications. 84 85### Modules to Import 86 87```js 88import Notification from '@ohos.notification'; 89``` 90 91 92 93### Subscribing to Notifications 94 95The notification recipient preferentially initiates a notification subscription request to the notification subsystem. 96 97```js 98var subscriber = { 99 onConsume: function (data) { 100 let req = data.request; 101 console.info('===>onConsume callback req.id: ' + req.id); 102 }, 103 onCancel: function (data) { 104 let req = data.request; 105 console.info('===>onCancel callback req.id: : ' + req.id); 106 }, 107 onUpdate: function (data) { 108 console.info('===>onUpdate in test===>'); 109 }, 110 onConnect: function () { 111 console.info('===>onConnect in test===>'); 112 }, 113 onDisconnect: function () { 114 console.info('===>onDisConnect in test===>'); 115 }, 116 onDestroy: function () { 117 console.info('===>onDestroy in test===>'); 118 }, 119 }; 120 121 Notification.subscribe(subscriber, (err) => { // This API uses an asynchronous callback to return the result. 122 if (err.code) { 123 console.error('===>failed to subscribe because ' + JSON.stringify(err)); 124 return; 125 } 126 console.info('===>subscribeTest success : ' + JSON.stringify(data)); 127 }); 128``` 129 130 131 132### Publishing Notifications 133 134##### Enabling Notification 135 136Before publishing a notification, check whether the notification feature is enabled for your application. By default, the feature is disabled. You can enabled it in notification settings. 137 138To 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. 139 140Normal text notification: 141 142```js 143// Create a NotificationRequest object. 144var notificationRequest = { 145 id: 1, 146 content: { 147 contentType: Notification.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT, 148 normal: { 149 title: "test_title", 150 text: "test_text", 151 additionalText: "test_additionalText" 152 } 153 } 154} 155 156// Publish the notification. 157Notification.publish(notificationRequest) .then(() => { 158 console.info('===>publish promise success req.id : ' + notificationRequest.id); 159}).catch((err) => { 160 console.error('===>publish promise failed because ' + JSON.stringify(err)); 161}); 162``` 163 164 165 166Notification containing **WantAgent**: 167 168For details about how to use **WantAgent**, see [WantAgent Development](https://gitee.com/openharmony/docs/blob/master/en/application-dev/ability/wantagent.md). 169 170- Create a **WantAgent** object. 171 172```js 173import wantAgent from '@ohos.wantAgent'; 174 175// WantAgentInfo object 176var wantAgentInfo = { 177 wants: [ 178 { 179 bundleName: 'ohos.samples.eTSNotification', 180 abilityName: 'ohos.samples.eTSNotification.MainAbility', 181 } 182 ], 183 operationType: wantAgent.OperationType.START_ABILITY, 184 requestCode: 0, 185 wantAgentFlags:[wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] 186} 187 188// WantAgent object 189var WantAgent; 190 191// getWantAgent callback 192function getWantAgentCallback(err, data) { 193 console.info("===>getWantAgentCallback===>"); 194 if (err.code == 0) { 195 WantAgent = data; 196 } else { 197 console.info('----getWantAgent failed!----'); 198 } 199} 200 201// Obtain the WantAgent object. 202wantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback) 203``` 204 205- Publish the notification. 206 207```js 208// Create a NotificationRequest object. 209var notificationRequest = { 210 content: { 211 contentType: Notification.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT, 212 normal: { 213 title: "AceApplication_Title", 214 text: "AceApplication_Text", 215 additionalText: "AceApplication_AdditionalText" 216 }, 217 }, 218 id: 1, 219 label: 'TEST', 220 wantAgent: WantAgent, 221 slotType: Notification.SlotType.OTHER_TYPES, 222 deliveryTime: new Date().getTime() 223} 224 225// Publish the notification. 226Notification.publish(notificationRequest) .then(() => { 227 console.info('===>publish promise success req.id : ' + notificationRequest.id); 228}).catch((err) => { 229 console.error('===>publish promise failed because ' + JSON.stringify(err)); 230}); 231``` 232 233 234 235- Cancel the notification. 236 237 An application can cancel a single notification or all notifications. An application can cancel only the notifications published by itself. 238 239```js 240// cancel callback 241function cancelCallback(err) { 242 console.info("===>cancelCallback===>"); 243} 244 245Notification.cancel(1, "label", cancelCallback) 246``` 247