004 Hongmeng application development - notification bar

Table of contents

1. Notification Overview

Introduction to Notifications

Notify business process

type of broadcast

Interface Description

Development preparation

2. Send ordinary text type notification

1. First initialize the broadcast request request

2. Then send the broadcast

3. The display effect is as follows

3. Send long text type broadcast

1. Construct the parameter request for sending broadcast

2. Then send the broadcast

3. The display effect is as follows

Precautions

4. Send multi-line text type broadcast

1. Construct the parameter request for sending broadcast

2. Send broadcast

3. Display effect

Precautions

5. Send picture type broadcast

the code

display effect

6. Send intent type broadcast

1. Create the wantAgent field

2. Construct the parameter request for sending broadcast

3. Send broadcast

4. Display the result


1. Notification Overview

Introduction to Notifications

Apps can send notification messages through the notification interface, and end users can view the notification content through the notification bar, or click the notification to open the app.

Common usage scenarios for notifications:

  • Display received short messages, instant messages, etc.

  • Display push messages of the application, such as advertisements, version updates, etc.

  • Displays currently ongoing events, such as downloads, etc.

HarmonyOS manages notification-type messages through ANS (Advanced Notification Service, notification system service), and supports multiple notification types, such as basic type notifications and progress bar type notifications.

Notify business process

The notification business process consists of a notification subsystem, a notification sender, and a notification subscriber.

A notification is generated from the notification sender, sent to the notification subsystem through IPC communication, and then distributed to the notification subscriber by the notification subsystem.

The system application also supports notification-related configurations, such as enable switches and configuration parameters, which are requested by the system configuration and sent to the notification subsystem for storage in memory and database.

type of broadcast

  • NOTIFICATION_CONTENT_BASIC_TEXT: normal text type
  • NOTIFICATION_CONTENT_LONG_TEXT: Long text type
  • NOTIFICATION_CONTENT_MULTILINE: multi-line text type
  • NOTIFICATION_CONTENT_PICTURE: Picture type

The types of broadcasts are mainly divided into ordinary text types, which send ordinary text broadcasts; long text types, which send long text type broadcasts; multi-line text types, which can display text in multiple lines and send broadcasts; send picture type broadcasts.

Interface Description

The notification publishing interface is shown in the following table. Different publishing types of notifications carry different information in the fields of NotificationRequest.

interface name

describe

publish(request: NotificationRequest, callback: AsyncCallback<void>): void

Post a notice.

cancel(id: number, label: string, callback: AsyncCallback<void>): void

Cancels the specified notification.

cancelAll(callback: AsyncCallback<void>): void;

Suppresses all notifications from this app.

Development preparation

Guide package

import NotificationManager from '@ohos.notificationManager';

2. Send ordinary text type notification

1. First initialize the broadcast request request

let notificationRequest = {

  id: 1,

  content: {

    contentType: NotificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT, // 普通文本类型通知

    normal: {

      title: 'test_title'//标题,必选项

      text: 'test_text'//内容,必选项

      additionalText: 'test_additionalText'//附加信息,非必选

    }

  }

}

2. Then send the broadcast

@Entry

@Component

struct Index {

  build() {

    Row() {

      Column() {

        Button("发送普通Notification").onClick(_ => {

          NotificationManager.publish(notificationRequest, (err) => {

            if (err) {

              console.error(`[ANS] failed to publish, error[${err}]`);

              return;

            }

            console.info(`[ANS] publish success`);

          });

        }).margin({ bottom: 20 })

      }.alignItems(HorizontalAlign.Start).padding(20)

      .width('100%')

    }.alignItems(VerticalAlign.Top)

    .height('100%')

  }

}

3. The display effect is as follows

Pull down the notification bar after clicking the send normal broadcast button

3. Send long text type broadcast

The long text type notification inherits the fields of the normal text type, and at the same time adds the long text content, content summary and title when the notification is expanded. The default display of the notification is the same as the normal text. After expanding, the title is displayed as the expanded title content, and the content is the long text content.

1. Construct the parameter request for sending broadcast

let notificationRequestLong = {

  id: 2,

  content: {

    contentType: NotificationManager.ContentType.NOTIFICATION_CONTENT_LONG_TEXT, // 长文本类型通知

    longText: {

      title: 'test_title',

      text: 'test_text',

      additionalText: 'test_additionalText',

      longText: 'test_longTextssssssssssssssssssssssssssssssssssssss',

      briefText: 'test_briefText',

      expandedTitle: 'test_expandedTitle',

    }

  }

}

2. Then send the broadcast

@Entry

@Component

struct Index {

  build() {

    Row() {

      Column() {

        Button("发送长文本Notification").onClick(_ => {

          NotificationManager.publish(notificationRequestLong, (err) => {

            if (err) {

              console.error(`[ANS] failed to publish, error[${err}]`);

              return;

            }

            console.info(`[ANS] publish success`);

          });

        }).margin({ bottom: 20 })

      }.alignItems(HorizontalAlign.Start).padding(20)

      .width('100%')

    }.alignItems(VerticalAlign.Top)

    .height('100%')

  }

}

3. The display effect is as follows

After clicking the button and then pulling down the notification bar to display the effect

Precautions

  • The current test found that the long text should be long enough. If it is not long enough, only the long text content will be displayed, and the normal text content will not be displayed.

4. Send multi-line text type broadcast

The multi-line text type notification inherits the fields of the normal text type, and adds multi-line text content, content summary and title when the notification is expanded. The default display of the notification is the same as the normal text. After expanding, the title is displayed as the expanded title content, and the multi-line text content is displayed in multiple lines.

1. Construct the parameter request for sending broadcast

let notificationRequestLines = {

  id: 3,

  content: {

    contentType: NotificationManager.ContentType.NOTIFICATION_CONTENT_MULTILINE, // 多行文本类型通知

    multiLine: {

      title: 'test_title',

      text: 'test_text',

      briefText: 'test_briefText',

      longTitle: 'test_longTitle',

      lines: ['line_01''line_02''line_03''line_04'],

    }

  }

}

2. Send broadcast

@Entry

@Component

struct Index {

  build() {

    Row() {

      Column() {

        Button("发送多行Notification").onClick(_ => {

          NotificationManager.publish(notificationRequestLines, (err) => {

            if (err) {

              console.error(`[ANS] failed to publish, error[${err}]`);

              return;

            }

            console.info(`[ANS] publish success`);

          });

        }).margin({ bottom: 20 })

      }.alignItems(HorizontalAlign.Start).padding(20)

      .width('100%')

    }.alignItems(VerticalAlign.Top)

    .height('100%')

  }

}

3. Display effect

Pull down the notification bar after clicking

Precautions

  • If there is only one line of text, only multi-line text content will be displayed, and normal text content will not be displayed

5. Send picture type broadcast

The image type notification inherits the fields of the ordinary text type, and adds the image content, content summary, and title when the notification is expanded. The image content is a PixelMap object, and its size cannot exceed 2M.

the code

@Entry

@Component

struct Index {

  build() {

    Row() {

      Column() {

        Button("发送Image Notification").onClick(_ => {

          // 图片构造

          const color = new ArrayBuffer(60000);

          let bufferArr = new Uint8Array(color);

          for (var i = 0; i<bufferArr.byteLength;i++) {

            bufferArr[i++] = 60;

            bufferArr[i++] = 20;

            bufferArr[i++] = 220;

            bufferArr[i] = 100;

          }

          let opts = { editable:true, pixelFormat:image.PixelMapFormat.RGBA_8888,size: {height:100, width : 150}};

          image

            .createPixelMap(color, opts)

            .then( value => {

              value.getImageInfo().then(imageInfo => {

                console.log("=====size: ====" + JSON.stringify(imageInfo.size));

              }).catch(err => {

                console.error("Failed to obtain the image pixel map information." + JSON.stringify(err));

                return;

              })

              let notificationRequest = {

                id: 1,

                content: {

                  contentType: NotificationManager.ContentType.NOTIFICATION_CONTENT_PICTURE,

                  picture: {

                    title: 'test_title',

                    text: 'test_text',

                    additionalText: 'test_additionalText',

                    picture: value,

                    briefText: 'test_briefText',

                    expandedTitle: 'test_expandedTitle',

                  }

                },

              }

              // 发送通知

              NotificationManager.publish(notificationRequest, (err) => {

                if (err) {

                  console.error(`[ANS] failed to publish, error[${err}]`);

                  return;

                }

                console.info(`[ANS] publish success `);

              });

            }).catch(err=>{

              console.error('create pixelmap failed =========='+ JSON.stringify(err));

              return;

            })

        }).margin({ bottom: 20 })

      }.alignItems(HorizontalAlign.Start).padding(20)

      .width('100%')

    }.alignItems(VerticalAlign.Top)

    .height('100%')

  }

}

display effect

After clicking the button, pull down the notification bar to display

6. Send intent type broadcast

Intent-type broadcasts are broadcasts that can be clicked and jump to the page after sending. Intent-type notifications inherit the normal text-type fields and add the wantAgent field. This parameter means which page to jump to

1. Create the wantAgent field

// 通过WantAgentInfo的operationType设置动作类型。

let wantAgentInfoDisplay = {

  wants: [

      {

        deviceId: '',

        bundleName: 'com.example.notificationtest',

        abilityName: 'MainAbility'

      }

  ],

  operationType: wantAgent.OperationType.START_ABILITY,

  requestCode: 0,

  wantAgentFlags: [wantAgent.WantAgentFlags.CONSTANT_FLAG]

}

@Entry

@Component

struct NotificationWantAgent {

  @State message: string = 'Hello World'

  build() {

    Row() {

      Column() {

        Button("意图通知").onClick(_ => {

          // 创建WantAgent

          wantAgent.getWantAgent(wantAgentInfoDisplay, (err, data) => {

            if (err) {

              console.error('[WantAgent]getWantAgent err=' + JSON.stringify(err));

            else {

              console.info('[WantAgent]getWantAgent success');

            }

          });

        })

      }.padding(20).alignItems(HorizontalAlign.Start)

      .width('100%')

    }

    .height('100%').alignItems(VerticalAlign.Top)

  }

}

The data obtained above is the wantAgent parameter

2.构建发送广播的参数request

let notificationRequest = {

                content: {

                  contentType: NotificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT,

                  normal: {

                    title: 'Test_Title',

                    text: 'Test_Text',

                    additionalText: 'Test_AdditionalText',

                  },

                },

                id: 6,

                label: 'TEST',

                wantAgent: data,

              }

3.发送广播

// 通知发送

NotificationManager.publish(notificationRequest, (err) => {

    if (err) {

        console.error(`[ANS] failed to publish, error[${err}]`);

        return;

    }

    console.info(`[ANS] publish success `);

});

4.显示结果

点击后下拉通知栏点击通知栏

Guess you like

Origin blog.csdn.net/gongjdde/article/details/130319420