[Mid-Autumn Festival and National Day Continuous Updates] HarmonyOS manages and publishes notification messages (Part 2)

1. Publish progress bar type notification

Progress bar notification is also a common notification type, mainly used for file downloading and transaction processing progress display. HarmonyOS provides a progress bar template. The notification application sets the attribute values ​​of the progress bar template, such as template name and template data, and sends them to the notification bar for display through the notification subsystem.

Currently, the system template only supports progress bar templates. The data parameter in the notification template NotificationTemplate is user-defined data, which is used to display data related to the module. The effect is shown in the figure below.

Interface Description

isSupportTemplate() is to query whether the template supports the interface. Currently, only progress bar templates are supported.

Interface name

describe

isSupportTemplate(templateName: string, callback: AsyncCallback<boolean>): void

Query whether the template exists.

Development steps

1. Import the module.

import NotificationManager from '@ohos.notificationManager';

2. Whether the system supports the progress bar template, the query result is that the downloadTemplate template class notification is supported.

NotificationManager.isSupportTemplate('downloadTemplate').then((data) => {
       
       
  console.info(`[ANS] isSupportTemplate success`);
  let isSupportTpl: boolean = data; // isSupportTpl的值为true表示支持支持downloadTemplate模板类通知,false表示不支持
  // ...
}).catch((err) => {
       
       
  console.error(`[ANS] isSupportTemplate failed, error[${err}]`);
});

illustrate

After querying the progress bar template supported by the system, proceed with the subsequent steps.

1. Construct a progress bar template object and publish a notification.

let template = {
       
       
  name:'downloadTemplate',
  data: {
       
       
    title: '标题:',
    fileName: 'music.mp4',
    progressValue: 30,
    progressMaxValue:100,
  }
}
//构造NotificationRequest对象
let notificationRquest = {
       
       
  id: 1,
  slotType: notify.SlotType.OTHER_TYPES,
  template: template,
  content: {
       
       
    contentType: notify.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT,
    normal: {
       
       
      title: template.data.title + template.data.fileName,
      text: "sendTemplate",
      additionalText: "30%"
    }
  },
  deliveryTime: new Date().getTime(),
  showDeliveryTime: true
}
notify.publish(notificationRquest).then(() => {
       
       
  console.info(`[ANS] publish success `);
}).catch((err) => {
       
       
  console.error(`[ANS] failed to publish, error[${err}]`);
});

2. Add behavioral intent to notifications

WantAgent provides the ability to encapsulate behavioral intentions. The behavioral intentions mentioned here mainly refer to the ability to pull up specified application components and publish public events. HarmonyOS supports passing WantAgent from the publisher to the receiver in the form of notifications, thereby triggering the intent specified in the WantAgent on the receiver. For example, when the publisher of a notification message publishes a notification, it is usually expected that the user can click and pull up the target application component through the notification bar. In order to achieve this goal, developers can encapsulate the WantAgent into the notification message. When the system receives the WantAgent, it triggers the WantAgent's intent when the user clicks on the notification bar, thus pulling up the target application component.

The implementation method of adding behavioral intentions to notifications is as shown in the figure below: the application that publishes the notification applies for the WantAgent from the application component management service AMS (Ability Manager Service), and then sends it to the desktop along with other notification information. When the user clicks the notification on the desktop notification bar When, the WantAgent action is triggered.

Figure 1  Notification operation mechanism carrying behavioral intentions

Interface Description

For specific interface description, please see the WantAgent interface document .

Interface name

describe

getWantAgent(info: WantAgentInfo, callback: AsyncCallback<WantAgent>): void

Create WantAgent.

trigger(agent: WantAgent, triggerInfo: TriggerInfo, callback?: Callback<CompleteData>): void

Trigger WantAgent intent.

cancel(agent: WantAgent, callback: AsyncCallback<void>): void

Cancel WantAgent.

getWant(agent: WantAgent, callback: AsyncCallback<Want>): void

Get the WantAgent's want.

equal(agent: WantAgent, otherAgent: WantAgent, callback: AsyncCallback<boolean>): void

Determine whether two WantAgent instances are equal.

Development steps

1. Import the module.

import NotificationManager from '@ohos.notificationManager';
import wantAgent from '@ohos.app.ability.wantAgent';

2. Create WantAgentInfo information.

Scenario 1: Create the WantAgentInfo information of the WantAgent that pulls up the Ability.

let wantAgentObj = null; // 用于保存创建成功的wantAgent对象,后续使用其完成触发的动作。

// 通过WantAgentInfo的operationType设置动作类型。
let wantAgentInfo = {
       
       
    wants: [
        {
       
       
            deviceId: '',
            bundleName: 'com.example.test',
            abilityName: 'com.example.test.MainAbility',
            action: '',
            entities: [],
            uri: '',
            parameters: {}
        }
    ],
    operationType: wantAgent.OperationType.START_ABILITY,
    requestCode: 0,
    wantAgentFlags:[wantAgent.WantAgentFlags.CONSTANT_FLAG]
}

Scenario 2: Create the WantAgentInfo information of the WantAgent that publishes public events .

let wantAgentObj = null; // 用于保存创建成功的WantAgent对象,后续使用其完成触发的动作。

// wantAgentInfo
let wantAgentInfo = {
       
       
    wants: [
        {
       
       
            action: 'event_name', // 设置事件名。
            parameters: {},
        }
    ],
    operationType: wantAgent.OperationType.SEND_COMMON_EVENT,
    requestCode: 0,
    wantAgentFlags: [wantAgent.WantAgentFlags.CONSTANT_FLAG],
}

3. Create WantAgent.

// 创建WantAgent
wantAgent.getWantAgent(wantAgentInfo, (err, data) => {
       
       
    if (err) {
       
       
        console.error('[WantAgent]getWantAgent err=' + JSON.stringify(err));
    } else {
       
       
        console.info('[WantAgent]getWantAgent success');
        wantAgentObj = data;
    }
});

4. Construct the NotificationRequest object.

// 构造NotificationRequest对象
let notificationRequest = {
       
       
    content: {
       
       
        contentType: NotificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT,
        normal: {
       
       
            title: 'Test_Title',
            text: 'Test_Text',
            additionalText: 'Test_AdditionalText',
        },
    },
    id: 1,
    label: 'TEST',
    wantAgent: wantAgentObj,
}

5. Publish WantAgent notification.

// 通知发送
NotificationManager.publish(notificationRequest, (err) => {
       
       
    if (err) {
       
       
        console.error(`[ANS] failed to publish, error[${err}]`);
        return;
    }
    console.info(`[ANS] publish success `);
});

6. The user can trigger WantAgent's action by clicking on the notification on the notification bar.

Guess you like

Origin blog.csdn.net/HarmonyOSDev/article/details/133313171
Recommended