• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Publishing a Live View Notification (for System Applications Only)
2
3Live view notifications enable users to get the latest updates of tasks in real time. Based on the implementation mechanism and usage scenario, there are two types of live view notifications:
4
5- System live view: displays the real-time progress of continuous tasks such as voice recording, screen recording, audio and video playback, timing, and calling. Such type of notification is not stored persistently, and its lifecycle is consistent with that of the notification publisher.
6
7- Common live view: displays the real-time progress of lifestyle services, such as takeout, taxi hailing, flight, and sports events, as well as continuous tasks. Such type of notification has a lifecycle. If the notification is not updated within 4 hours or has been retained for 8 hours, it is automatically deleted. You can customize the notification retention period (how long the notification will be retained in the notification panel). A common live view notification is stored persistently once it is created or updated. After the device is powered on or restarted, the notification in the created or updated state can be restored.
8
9**Table 1** Types of live view notifications
10
11| Type                                                  | Value| Description               |
12| ------------------------------------------------------ | --- | ------------------ |
13| NOTIFICATION_CONTENT_SYSTEM_LIVE_VIEW<sup>11+</sup>    | 5  | System live view notification.   |
14| NOTIFICATION_CONTENT_LIVE_VIEW<sup>11+</sup>           | 6  | Common live view notification.|
15## Available APIs
16
17The following table describes the APIs for notification publishing. You specify the notification information – content, ID, slot type, and publish time – by setting the [NotificationRequest](../reference/apis-notification-kit/js-apis-inner-notification-notificationRequest.md#notificationrequest) parameter in the APIs.
18
19| **API**| **Description**|
20| -------- | -------- |
21| [publish](../reference/apis-notification-kit/js-apis-notificationManager.md#notificationmanagerpublish)(request: NotificationRequest, callback: AsyncCallback&lt;void&gt;): void | Publishes a notification.                |
22| [cancel](../reference/apis-notification-kit/js-apis-notificationManager.md#notificationmanagercancel)(id: number, label: string, callback: AsyncCallback&lt;void&gt;): void | Cancels a specified notification.     |
23
24
25## How to Develop
26
271. [Request notification authorization](notification-enable.md). Your application can send notifications only after obtaining user authorization.
28
292. Import the modules.
30
31   ```ts
32   import notificationManager from '@ohos.notificationManager';
33   import Base from '@ohos.base';
34   ```
35
363. Publish a notification.
37
38   - In addition to the parameters in the normal text notification, the system live view notification provides the **typeCode**, **capsule**, **button**, **time**, and **progress** parameters. For details, see [NotificationSystemLiveViewContent](../reference/apis-notification-kit/js-apis-inner-notification-notificationContent.md#notificationsystemliveviewcontent).
39
40      ```ts
41      import image from '@ohos.multimedia.image';
42      import notificationSubscribe from '@ohos.notificationSubscribe';
43
44      let imagePixelMap: image.PixelMap | undefined = undefined; // Obtain the image pixel map information.
45      let color = new ArrayBuffer(4);
46      image.createPixelMap(color, {
47        size: {
48          height: 1,
49          width: 1
50        }
51      }).then((data: image.PixelMap) => {
52        imagePixelMap = data;
53      }).catch((err: Base.BusinessError) => {
54        console.log(`createPixelMap failed, error: ${err}`);
55      })
56      if(imagePixelMap !== undefined) {
57        let notificationRequest: notificationManager.NotificationRequest = {
58          notificationSlotType: notificationManager.SlotType.LIVE_VIEW, // Live view
59          id: 0, // Notification ID. The default value is 0.
60          content: {
61            notificationContentType : notificationManager.ContentType.NOTIFICATION_CONTENT_SYSTEM_LIVE_VIEW,
62            systemLiveView: {
63              title: "test_title",
64              text:"test_text",
65              typeCode: 1, // Type of the invoking service.
66              // Button
67              button: {
68                names: ["buttonName1"],
69                icons: [imagePixelMap],
70              },
71              // Capsule
72              capsule: {
73                title: "testTitle",
74                icon: imagePixelMap,
75                backgroundColor: "testColor",
76              },
77              // Progress. To update the progress, you only need to modify the progress value and publish the notification again.
78              progress: {
79                maxValue: 100,ss
80                currentValue: 21,
81                isPercentage: false,
82              },
83              // Time
84              time: {
85                initialTime: 12,
86                isCountDown: true,
87                isPaused: true,
88                isInTitle: false,
89              }
90            }
91          }
92        };
93        // subscribe callback
94        let subscribeCallback = (err: Base.BusinessError): void => {
95          if (err) {
96            console.error(`subscribe failed, code is ${err.code}, message is ${err.message}`);
97          } else {
98            console.info("subscribe success");
99          }
100        };
101        // publish callback
102        let publishCallback = (err: Base.BusinessError): void => {
103          if (err) {
104            console.error(`publish failed, code is ${err.code}, message is ${err.message}`);
105          } else {
106            console.info("publish success");
107          }
108        };
109        // Button callback (It is returned when the button is touched. You can determine how to process the callback.)
110        let onResponseCallback = (id:number, option:notificationManager.ButtonOptions) => {
111          console.info("response callback: " + JSON.stringify(option) + "notificationId" + id);
112        }
113        let systemLiveViewSubscriber: notificationManager.SystemLiveViewSubscriber  = {
114          onResponse: onResponseCallback
115        };
116        // Invoked when the subscriber cancels the notification.
117        let onCancelCallback = (data: notificationSubscribe.SubscribeCallbackData) => {
118          console.info("Cancel callback: " + JSON.stringify(data));
119        }
120        let notificationSubscriber: notificationSubscribe.NotificationSubscriber = {
121          onCancel: onCancelCallback
122        };
123        let info: notificationSubscribe.NotificationSubscribeInfo = {
124          bundleNames: ["bundleName1"],
125          userId: 123
126        };
127        // Subscribe to the notification.
128        notificationSubscribe.subscribe(notificationSubscriber, info, subscribeCallback);
129        // Subscribe to the system live view notification (button).
130        notificationManager.subscribeSystemLiveView(systemLiveViewSubscriber);
131        // Publish the notification.
132        notificationManager.publish(notificationRequest, publishCallback);
133      }
134      ```
135
136   - In addition to the parameters in the normal text notification, the common live view provides the **status**, **version**, **extraInfo**, and **pictureInfo** parameters. For details, see [NotificationLiveViewContent](../reference/apis-notification-kit/js-apis-inner-notification-notificationContent-sys.md#notificationliveviewcontent11).
137
138      ```ts
139      import Want from '@ohos.app.ability.Want';
140      import wantAgent, {WantAgent as _wantAgent} from '@ohos.app.ability.wantAgent';
141
142      let wantAgentInfo: wantAgent.WantAgentInfo = {
143        wants: [
144            {
145                deviceId: '',
146                bundleName: 'com.example.myapplication',
147                abilityName: 'EntryAbility',
148                action: '',
149                entities: [],
150                uri: '',
151                parameters: {}
152            }
153        ],
154        operationType: wantAgent.OperationType.START_ABILITY,
155        requestCode: 0,
156        wantAgentFlags: [wantAgent.WantAgentFlags.CONSTANT_FLAG]
157      }
158      let notificationRequest: notificationManager.NotificationRequest = {
159        id: 1,
160        content: {
161          notificationContentType: notificationManager.ContentType.NOTIFICATION_CONTENT_LIVE_VIEW,
162          liveView: {
163            status: notificationManager.LiveViewStatus.LIVE_VIEW_CREATE,
164            version: 1,
165            extraInfo: {
166              "event": "TAXI",
167              "isMute": false,
168              "primaryData.title": "primary title",
169              "primaryData.content": [{ text: "text1", textColor: "#FFFFFFFF"}, { text: "text2", textColor: "#FFFFFFFF"}],
170              "primaryData.keepTime": 60,
171              "primaryData.extend.text": "extendData text",
172              "primaryData.extend.type": 1,
173              "PickupLayout.layoutType": 4,
174              "PickupLayout.title": "layout title",
175              "PickupLayout.content": "layout content",
176              "PickupLayout.underlineColor": "#FFFFFFFF",
177              "CapsuleData.status": 1,
178              "CapsuleData.type": 1,
179              "CapsuleData.backgroundColor": "#FFFFFFFF",
180              "CapsuleData.title": "capsule title",
181              "CapsuleData.content": "capsule content",
182              "TimerCapsule.content": "capsule title",
183              "TimerCapsule.initialtime": 7349485944,
184              "TimerCapsule.isCountdown": false,
185              "TimerCapsule.isPause": true
186            }
187          }
188        },
189        notificationSlotType: notificationManager.SlotType.LIVE_VIEW,
190        isOngoing: true,
191        isUnremovable: false,
192        autoDeletedTime: 500,
193        wantAgent: await WantAgent.getWantAgent(WantAgentInfo),
194        extraInfo: {
195          'testKey': 'testValue'
196        },
197      }
198
199      notificationManager.publish(notificationRequest, (err:Base.BusinessError) => {
200        if (err) {
201          console.error(`Failed to publish notification. Code is ${err.code}, message is ${err.message}`);
202          return;
203        }
204        console.info('Succeeded in publishing notification.');
205      });
206      ```
207