HarmonyOS:给您的应用添加通知

news/2025/2/4 20:38:48 标签: harmonyos, 鸿蒙

一、通知介绍

通知旨在让用户以合适的方式及时获得有用的新消息,帮助用户高效地处理任务。应用可以通过通知接口发送通知消息,用户可以通过通知栏查看通知内容,也可以点击通知来打开应用,通知主要有以下使用场景:

  • 显示接收到的短消息、即时消息等。
  • 显示应用的推送消息,如广告、版本更新等。
  • 显示当前正在进行的事件,如下载等。

1.1 通知表现形式

通知会在不同场景以不同形式提示用户,例如通知在状态栏上显示为图标、在通知栏上会显示通知详细信息。重要的信息还可以使用横幅通知,浮动在界面顶部显示。

在这里插入图片描述

1.2 通知结构

下面以基础的文本通知为例,介绍通知的基本结构。

在这里插入图片描述

  1. 通知小图标:表示通知的功能与类型。
  2. 通知名称:应用名称或功能名称。
  3. 时间:发送通知的时间,系统默认显示。
  4. 展开箭头:点击标题区,展开被折叠的内容和按钮。若无折叠的内容和按钮,不显示此箭头。
  5. 内容标题:描述简明概要。
  6. 内容详情:描述具体内容或详情。

二、请求通知授权

应用需要获取用户授权才能发送通知。在通知发布前调用requestEnableNotification()方法,弹窗让用户选择是否允许发送通知,后续再次调用requestEnableNotification()方法时,则不再弹窗。

2.1 接口说明

通知授权接口功能介绍

接口名描述
isNotificationEnabled():Promise查询通知是否授权。
requestEnableNotification(context: UIAbilityContext): Promise请求发送通知的许可,第一次调用会弹窗让用户选择。
2.2 开发步骤

效果图1

在这里插入图片描述

效果图2

在这里插入图片描述

  1. 导入NotificationManager模块
import { notificationManager } from '@kit.NotificationKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
import { common } from '@kit.AbilityKit';

const TAG: string = '[PublishOperation]';
const DOMAIN_NUMBER: number = 0xFF00;
  1. 请求通知授权

可通过requestEnableNotification的错误码判断用户是否授权。若返回的错误码为1600004,即为拒绝授权。

let context = getContext(this) as common.UIAbilityContext;
notificationManager.isNotificationEnabled().then((data: boolean) => {
  hilog.info(DOMAIN_NUMBER, TAG, "isNotificationEnabled success, data: " + JSON.stringify(data));
  if(!data){
    notificationManager.requestEnableNotification(context).then(() => {
      hilog.info(DOMAIN_NUMBER, TAG, `[ANS] requestEnableNotification success`);
    }).catch((err : BusinessError) => {
      if(1600004 == err.code){
        hilog.error(DOMAIN_NUMBER, TAG, `[ANS] requestEnableNotification refused, code is ${err.code}, message is ${err.message}`);
      } else {
        hilog.error(DOMAIN_NUMBER, TAG, `[ANS] requestEnableNotification failed, code is ${err.code}, message is ${err.message}`);
      }
    });
  }
}).catch((err : BusinessError) => {
    hilog.error(DOMAIN_NUMBER, TAG, `isNotificationEnabled fail, code is ${err.code}, message is ${err.message}`);
});

三、创建通知

本节将介绍几种常见类型通知的创建,在创建通知前需要先导入notificationManager模块,该模块提供通知管理的能力,包括发布、取消发布通知,创建、获取、移除通知通道等能力。

2.1 发布基础类型通知

基础类型通知主要应用于发送短信息、提示信息、广告推送等,支持普通文本类型、长文本类型、多行文本类型,可以通过ContentType指定通知的内容类型。下面以普通文本类型为例来介绍基础通知的发布,其它基础类型您可以查阅API。

发布普通文本类型通知,需要设置ContentType类型为ContentType.NOTIFICATION_CONTENT_BASIC_TEXT。

效果图

在这里插入图片描述

NotificationDemo1.ets 代码


import { notificationManager } from '@kit.NotificationKit'
import { common } from '@kit.AbilityKit'
import { BusinessError } from '@kit.BasicServicesKit';

@Entry
@Component
struct NotificationDemo1 {
  @State message: string = '应用消息通知';

  checkNotificationPerrmission() {
    let context = getContext(this) as common.UIAbilityContext
    notificationManager.isNotificationEnabled().then((data: boolean) => {
      if (data) {
        console.log("已获取通知权限")
        this.publishNotification()
        return
      }
      console.log("发起请求通知授权")
      notificationManager.requestEnableNotification(context).then(() => {
        console.log("发起请求通知授权成功")
        this.publishNotification()
      }).catch((err: BusinessError) => {
        if (1600004 == err.code) {
          console.log("发起请求通知授权被拒绝,错误码: ", err.code)
        } else {
          console.log("发起请求通知授权失败,错误码: ", err.code)
        }
      })

    })
  }

  /**
   * 发布消息通知
   */
  publishNotification() {
    let notificationRequest: notificationManager.NotificationRequest = {
      // 描述通知的请求
      id: 1, // 通知ID
      content: {
        // 通知内容
        notificationContentType: notificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT, // 普通文本类型通知
        normal: {
          // 基本类型通知内容
          title: '通知内容标题',
          text: '通知内容详情'
        }
      }
    }

    notificationManager.publish(notificationRequest).then(() => {
      console.info("消息通知发布成功")
    }).catch((err: Error) => {
      console.error(`消息通知发布失败了, 异常信息是: ${err}`)
    })
  }

  build() {
    Column() {
      Text(this.message)
        .id('NotificationDemo1HelloWorld')
        .fontSize(30)
        .fontWeight(FontWeight.Bold)
      Button("发送通知")
        .onClick((_event) => {
          this.checkNotificationPerrmission()
        })
    }
    .height('100%')
    .width('100%')
  }
}
2.2 发布进度类型通知

进度条通知也是常见的通知类型,主要应用于文件下载、事务处理进度显示。目前系统模板仅支持进度条模板,效果示意如下图所示:

在这里插入图片描述

在发布进度类型通知前需要查询系统是否支持进度条模板。

  checkisSupportTemplate() {
    notificationManager.isSupportTemplate('downloadTemplate').then(isSupport => {
      if (!isSupport) {
        promptAction.showToast({
          message: "该设备不支持进度类型通知"
        })

        return
      }

    });
  }

构造进度条模板,name字段当前需要固定配置为downloadTemplate。

publishNotificationDownloadTemplate() {
    let templateData: notificationManager.NotificationTemplate = {
      name: 'downloadTemplate',
      data: {
        progressValue: 60, // 当前进度值
        progressMaxValue: 100, // 最大进度值
        title: 'File Title3',// 注意这里的标题和文件名要有,否则会报错,参数无效:Error: Invalid parameter
        fileName: '3music.mp4'
      }
    }

    let notificationRequest: notificationManager.NotificationRequest = {
      id: 1,
      content: {
        notificationContentType: notificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT,
        normal: {
          title: '文件下载:music.mp4',
          text: 'senTemplate',
          additionalText: '60%'
        }
      },
      template: template
    }
    // 发布通知
    notificationManager.publish(notificationRequest).then(() => {
      console.info(`publish success`);
    }).catch((err: Error) => {
      console.error(`publish failed,message is ${err}`);
    })
  }
2.4 更新通知

在发出通知后,使用您之前使用的相同通知ID,再次调用notificationManager.publish来实现通知的更新。如果之前的通知是关闭的,将会创建新通知。

2.5 移除通知
  • 通过通知ID和通知标签取消已发布的通知。
    notificationManager.cancel(notificationId)
  • 取消所有已发布的通知。
    notificationManager.cancelAll()

四、设置通知通道

通过通知通道,您可让通知有不同的表现形式,比如社交类型的通知是横幅显示的,并且有提示音,而一般的通知则不会横幅显示,您可以使用slotType来实现,设置slotType为SlotType.SOCIAL_COMMUNICATION,表示为社交类型通知。示例代码如下:

notificationManager.addSlot(notificationManager.SlotType.SOCIAL_COMMUNICATION).then(() => {
  console.info("addSlot success");
}).catch((err: Base.BusinessError) => {
  console.error(`addSlot fail: ${JSON.stringify(err)}`);
});

通知通道类型主要有以下几种:

  • SlotType.SOCIAL_COMMUNICATION:社交类型,状态栏中显示通知图标,有横幅和提示音。
  • SlotType.SERVICE_INFORMATION:服务类型,状态栏中显示通知图标,没有横幅但有提示音。
  • SlotType.CONTENT_INFORMATION:内容类型,状态栏中显示通知图标,但没有横幅或提示音。
  • SlotType.OTHER_TYPES:其它类型,状态栏中不显示通知图标,且没有横幅或提示音。

效果图

在这里插入图片描述

五、创建通知组

将不同类型的通知分为不同的组,以便用户可以更好的管理他们。当同组的通知有多条的时候,会自动折叠起来,避免通知比较多的时候,通知界面比较杂乱,例如当通知栏里有聊天消息通知和商品推荐通知时,我们只需要通过设置字段groupName,就可以对通知进行分组,给groupName设置不同的值可以将通知分为不同的组。

效果图

在这里插入图片描述

可以使用groupName来指定通知组来实现,示例代码如下:

testGroupName() {
    let notifyId = 0;
    let chatRequest1: notificationManager.NotificationRequest = {
      id: notifyId++,
      groupName: 'ChatGroup',
      content: {
        notificationContentType: notificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT,
        normal: {
          title: '新框架即将发布1',
          text: '新框架优化代码结构,提升性能1'
        }
      }
    };

    notificationManager.publish(chatRequest1).then(() => {
      console.info("chatRequest1 消息通知发布成功")
    }).catch((err: Error) => {
      console.error(`chatRequest1 消息通知发布失败了, 异常信息是: ${err}`)
    });

    let chatRequest2: notificationManager.NotificationRequest = {
      id: notifyId++,
      groupName: 'ChatGroup',
      content: {
        notificationContentType: notificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT,
        normal: {
          title: '新框架即将发布2',
          text: '新框架优化代码结构,提升性能2'
        }
      }
    };

    notificationManager.publish(chatRequest2).then(() => {
      console.info("chatRequest2 消息通知发布成功")
    }).catch((err: Error) => {
      console.error(`chatRequest2 消息通知发布失败了, 异常信息是: ${err}`)
    });

    let productRequest1: notificationManager.NotificationRequest = {
      id: notifyId++,
      groupName: 'ProductGroup',
      content: {
        notificationContentType: notificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT,
        normal: {
          title: '有机食品 1',
          text: '新鲜蔬菜,健康1'
        }
      }
    };

    notificationManager.publish(productRequest1).then(() => {
      console.info("productRequest1 消息通知发布成功")
    }).catch((err: Error) => {
      console.error(`productRequest1 消息通知发布失败了, 异常信息是: ${err}`)
    })

    let productRequest2: notificationManager.NotificationRequest = {
      id: notifyId++,
      groupName: 'ProductGroup',
      content: {
        notificationContentType: notificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT,
        normal: {
          title: '有机食品 2',
          text: '新鲜蔬菜,健康2'
        }
      }
    };

    notificationManager.publish(productRequest2).then(() => {
      console.info("productRequest2 消息通知发布成功")
    }).catch((err: Error) => {
      console.error(`productRequest2 消息通知发布失败了, 异常信息是: ${err}`)
    });
  }

六、为通知添加行为意图

WantAgent提供了封装行为意图的能力,这里所说的行为意图主要是指拉起指定的应用组件及发布公共事件等能力。给通知添加行为意图后,点击通知后可以拉起指定的UIAbility或者发布公共事件,您可以按照以下步骤来实现:

6.1 导入模块。
import { notificationManager } from '@kit.NotificationKit'; 
import { wantAgent, WantAgent } from '@kit.AbilityKit';

创建WantAgentInfo信息。

场景一:拉起UIAbility

let wantAgentInfo = { 
  wants: [ 
    { 
      bundleName: "com.example.notification", 
      abilityName: "EntryAbility" 
    } 
  ], 
  operationType: wantAgent.OperationType.START_ABILITY, 
  requestCode: 100 
}

场景二:发布公共事件

let wantAgentInfo = { 
  wants: [ 
    { 
      action: 'event_name', // 设置事件名 
      parameters: {}, 
    } 
  ], 
  operationType: wantAgent.OperationType.SEND_COMMON_EVENT, 
  requestCode: 100, 
  wantAgentFlags: [wantAgent.WantAgentFlags.CONSTANT_FLAG], 
}
6.2 创建WantAgent对象
let wantAgentObj = null;  
wantAgent.getWantAgent(wantAgentInfo) 
  .then((data) => { 
    wantAgentObj = data; 
  }) 
  .catch((err: Error) => { 
    console.error(`get wantAgent failed because ${JSON.stringify(err)}`); 
  })
6.3 构造NotificationRequest对象
let notificationRequest: notificationManager.NotificationRequest = {
  id: 1, 
  content: { 
    notificationContentType: notificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT, 
    normal: { 
      title: "通知标题", 
      text: "通知内容" 
    } 
  }, 
  // wantAgentObj使用前需要保证已被赋值
  wantAgent: wantAgentObj!
};
6.4 发布WantAgent通知
notificationManager.publish(notificationRequest).then(() => { // 发布通知
  console.info("publish success"); 
}).catch((err: Error) => { 
  console.error(`publish failed, code is ${err.code}, message is ${err.message}`); 
});  

用户通过点击通知栏上的通知,即可触发WantAgent的动作。


http://www.niftyadmin.cn/n/5841795.html

相关文章

登录认证(5):过滤器:Filter

统一拦截 上文我们提到(登录认证(4):令牌技术),现在大部分项目都使用JWT令牌来进行会话跟踪,来完成登录功能。有了JWT令牌可以标识用户的登录状态,但是完整的登录逻辑如图所示&…

98,【6】 buuctf web [ISITDTU 2019]EasyPHP

进入靶场 代码 <?php // 高亮显示当前 PHP 文件的源代码&#xff0c;通常用于调试或展示代码&#xff0c;方便用户查看代码逻辑 highlight_file(__FILE__);// 从 GET 请求中获取名为 _ 的参数值&#xff0c;并赋值给变量 $_ // 符号用于抑制可能出现的错误信息&#xff…

排序算法--基数排序

核心思想是按位排序&#xff08;低位到高位&#xff09;。适用于定长的整数或字符串&#xff0c;如例如&#xff1a;手机号、身份证号排序。按数据的每一位从低位到高位&#xff08;或相反&#xff09;依次排序&#xff0c;每次排序使用稳定的算法&#xff08;如计数排序&#…

SliverAppBar的功能和用法

文章目录 1 概念介绍2 使用方法3 示例代码 我们在上一章回中介绍了SliverGrid组件相关的内容&#xff0c;本章回中将介绍SliverAppBar组件.闲话休提&#xff0c;让我们一起Talk Flutter吧。 1 概念介绍 我们在本章回中介绍的SliverAppBar和普通的AppBar类似&#xff0c;它们的…

自动驾驶---两轮自行车的自主导航

1 背景 无人驾驶汽车最早出现在DARPA的比赛中&#xff0c;从那个时刻开始&#xff0c;逐渐引起全球学者的注意&#xff0c;于是从上个世纪开始各大高校院所开始了无人汽车的研发。直到这两年&#xff0c;无人驾驶汽车才开始走进寻常百姓家&#xff0c;虽然目前市面上的乘用车还…

【02】智能合约与虚拟机

Solidity底层 ABI接口详解 ABI是什么? ABI&#xff1a;Application Binary Interface&#xff08;应用程序二进制接口&#xff09; 蚂蚁链BaaS平台提供的Cloud IDE&#xff0c;会在合约编译后&#xff0c;一并生成对应的ABI文件&#xff08;JSON格式描述&#xff09; ABI…

GRN前沿:利用DigNet从scRNA-seq数据中生成基于扩散的基因调控网络

1.论文原名&#xff1a;Diffusion-based generation of gene regulatory network from scRNA-seq data with DigNet 2.出版时间&#xff1a;2024.12.18 3.doi: 10.1101/gr.279551.124 摘要&#xff1a; 基因调控网络&#xff08;GRN&#xff09;在细胞内基因的身份和功能之间…

Python处理数据库:MySQL与SQLite详解

Python处理数据库&#xff1a;MySQL与SQLite详解 在数据处理和存储方面&#xff0c;数据库扮演着至关重要的角色。Python提供了多种与数据库交互的方式&#xff0c;其中pymysql库用于连接和操作MySQL数据库&#xff0c;而SQLite则是一种轻量级的嵌入式数据库&#xff0c;Pytho…