【HarmonyOS】消息通知场景的实现

            从今天开始,博主将开设一门新的专栏用来讲解市面上比较热门的技术 “鸿蒙开发”,对于刚接触这项技术的小伙伴在学习鸿蒙开发之前,有必要先了解一下鸿蒙,从你的角度来讲,你认为什么是鸿蒙呢?它出现的意义又是什么?鸿蒙仅仅是一个手机操作系统吗?它的出现能够和Android和IOS三分天下吗?它未来的潜力能否制霸整个手机市场呢?

抱着这样的疑问和对鸿蒙开发的好奇,让我们开始今天对消息通知的掌握吧!

目录

基础通知

进度条通知

通知意图


基础通知

在harmonyos当中提供了各种不同功能的通知来满足我们不同的业务需求,接下来我们首先开始对基础通知它的场景和实现方式进行讲解。

应用可以通过通知接口发送通知消息,提醒用户关注应用中的变化,用户可以在通知栏查看和操作通知内容。以下是基础通知的操作步骤:

1)导入 notification 模块:

import notificationManager from '@ohos.notificationManager';

2)发布通知:

// 构建通知请求
let request: notificationManager.NotificationRequest = {id: 10,content: { // 通知内容:... }
}
// 发布通知
notificationManager.publish(request).then(() => console.log('发布通知成功')).catch(reason => console.log('发布通知失败', JSON.stringify((reason))))

通知的类型主要有以下四种:

类型枚举说明
NOTIFICATION_CONTENT_BASIC_TEXT普通文本型
NOTIFICATION_CONTENT_LONG_TEXT长文本型
NOTIFICATION_CONTENT_MULTILINE多行文本型
NOTIFICATION_CONTENT_PICTURE图片型

3)取消通知:

// 取消指定id的通知
notificationManager.cancel(10)
// 取消当前应用所有通知
notificationManager.calcelAll()

接下来对基础通知的四种通知类型进行简单的讲解,具体使用参数使用可在publish出悬停,然后点击查阅API参考进行查看:

这里将常用的参数 SlotType 进行简单讲解一下,其下面的具体参数可参考以下的表格:

类型枚举说明状态栏图标提示音横幅
SOCIAL_COMMUNICATION社交类型
SERVICE_INFORMATION服务类型
CONTENT_INFORMATION内容类型
OTHER_TYPES其他

关于通知的消息需要在手机模拟器上才能显示,在本地预览器中是不能显示的:  

import notify from '@ohos.notificationManager'
import image from '@ohos.multimedia.image'
import { Header } from '../common/components/CommonComponents'@Entry
@Component
struct NotificationPage {// 全局任务ididx: number = 100// 图象pixel: PixelMapasync aboutToAppear() {// 获取资源管理器let rm = getContext(this).resourceManager;// 读取图片let file = await rm.getMediaContent($r('app.media.watchGT4'))// 创建PixelMapimage.createImageSource(file.buffer).createPixelMap().then(value => this.pixel = value).catch(reason => console.log('testTag', '加载图片异常', JSON.stringify(reason)))}build() {Column({space: 20}) {Header({title: '通知功能'})Button(`发送normalText通知`).onClick(() => this.publishNormalTextNotification())Button(`发送longText通知`).onClick(() => this.publishLongTextNotification())Button(`发送multiLine通知`).onClick(() => this.publishMultiLineNotification())Button(`发送Picture通知`).onClick(() => this.publishPictureNotification())}.width('100%').height('100%').padding(5).backgroundColor('#f1f2f3')}// 普通文本发送publishNormalTextNotification() {let request: notify.NotificationRequest = {id: this.idx++,content: {contentType: notify.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT,normal: {title: '通知标题' + this.idx,text: '通知内容详情',additionalText: '通知附加内容'}},showDeliveryTime: true,deliveryTime: new Date().getTime(),groupName: 'wechat',slotType: notify.SlotType.SOCIAL_COMMUNICATION}this.publish(request)}// 长文本发送publishLongTextNotification() {let request: notify.NotificationRequest = {id: this.idx++,content: {contentType: notify.ContentType.NOTIFICATION_CONTENT_LONG_TEXT,longText: {title: '通知标题' + this.idx,text: '通知内容详情',additionalText: '通知附加内容',longText: '通知中的长文本,我很长,我很长,我很长,我很长,我很长,我很长,我很长',briefText: '通知概要和总结',expandedTitle: '通知展开时的标题' + this.idx}}}this.publish(request)}// 多行文本发送publishMultiLineNotification() {let request: notify.NotificationRequest = {id: this.idx++,content: {contentType: notify.ContentType.NOTIFICATION_CONTENT_MULTILINE,multiLine: {title: '通知标题' + this.idx,text: '通知内容详情',additionalText: '通知附加内容',briefText: '通知概要和总结',longTitle: '展开时的标题,我很宽,我很宽,我很宽',lines: ['第一行','第二行','第三行','第四行',]}}}this.publish(request)}// 图片型文本发送publishPictureNotification() {let request: notify.NotificationRequest = {id: this.idx++,content: {contentType: notify.ContentType.NOTIFICATION_CONTENT_PICTURE,picture: {title: '通知标题' + this.idx,text: '通知内容详情',additionalText: '通知附加内容',briefText: '通知概要和总结',expandedTitle: '展开后标题' + this.idx,picture: this.pixel}}}this.publish(request)}private publish(request: notify.NotificationRequest) {notify.publish(request).then(() => console.log('notify test', '发送通知成功')).then(reason => console.log('notify test', '发送通知失败', JSON.stringify(reason)))}
}

呈现的效果如下:

进度条通知

进度条通知会展示一个动态的进度条,主要用于文件下载,长任务处理的进度显示,下面是实现进度条的基本步骤:

1)判断当前系统是否支持进度条模板

this.isSupport = await notify.isSupportTemplate('downloadTemplate')
if(!this.isSupport) {return 
}

2)定义通知请求

let template = {name: 'downloadTemplate', // 模板名称,必须是downloadTemplatedata: {progressValue: this.progressValue, // 进度条当前进度progressMaxValue: this.progressMaxValue // 进度条的最大值}
}
let request: notify.NotificationRequest = {id: this.notificationId,template: template,wantAgent: this.wantAgentInstance,content: {contentType: notify.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT,normal: {title: this.filename + ':  ' + this.state,text: '',additionalText: this.progressValue + '%'}}
}

接下来对进度条进行实现:

import notify from '@ohos.notificationManager'
import wantAgent, { WantAgent } from '@ohos.app.ability.wantAgent'
import promptAction from '@ohos.promptAction'enum DownloadState {NOT_BEGIN = '未开始',DOWNLOADING = '下载中',PAUSE = '已暂停',FINISHED = '已完成',
}@Component
export default struct DownloadCard {// 下载进度@State progressValue: number = 0progressMaxValue: number = 100// 任务状态@State state: DownloadState = DownloadState.NOT_BEGIN// 下载的文件名filename: string = '圣诞星.mp4'// 模拟下载的任务的idtaskId: number = -1// 通知idnotificationId: number = 999isSupport: boolean = falseasync aboutToAppear(){// 判断当前系统是否支持进度条模板this.isSupport = await notify.isSupportTemplate('downloadTemplate')}build() {Row({ space: 10 }) {Image($r('app.media.ic_files_video')).width(50)Column({ space: 5 }) {Row() {Text(this.filename)Text(`${this.progressValue}%`).fontColor('#c1c2c1')}.width('100%').justifyContent(FlexAlign.SpaceBetween)Progress({value: this.progressValue,total: this.progressMaxValue,})Row({ space: 5 }) {Text(`${(this.progressValue * 0.43).toFixed(2)}MB`).fontSize(14).fontColor('#c1c2c1')Blank()if (this.state === DownloadState.NOT_BEGIN) {Button('开始').downloadButton().onClick(() => this.download())} else if (this.state === DownloadState.DOWNLOADING) {Button('取消').downloadButton().backgroundColor('#d1d2d3').onClick(() => this.cancel())Button('暂停').downloadButton().onClick(() => this.pause())} else if (this.state === DownloadState.PAUSE) {Button('取消').downloadButton().backgroundColor('#d1d2d3').onClick(() => this.cancel())Button('继续').downloadButton().onClick(() => this.download())} else {Button('打开').downloadButton().onClick(() => this.open())}}.width('100%')}.layoutWeight(1)}.width('100%').borderRadius(20).padding(15).backgroundColor(Color.White)}cancel() {// 取消定时任务if(this.taskId > 0){clearInterval(this.taskId);this.taskId = -1}// 清理下载任务进度this.progressValue = 0// 标记任务状态:未开始this.state = DownloadState.NOT_BEGIN// 取消通知notify.cancel(this.notificationId)}download() {// 清理旧任务if(this.taskId > 0){clearInterval(this.taskId);}// 开启定时任务,模拟下载this.taskId = setInterval(() => {// 判断任务进度是否达到100if(this.progressValue >= 100){// 任务完成了,应该取消定时任务clearInterval(this.taskId)this.taskId = -1// 并且标记任务状态为已完成this.state = DownloadState.FINISHED// 发送通知this.publishDownloadNotification()return}// 模拟任务进度变更this.progressValue += 2// 发送通知this.publishDownloadNotification()}, 500)// 标记任务状态:下载中this.state = DownloadState.DOWNLOADING}pause() {// 取消定时任务if(this.taskId > 0){clearInterval(this.taskId);this.taskId = -1}// 标记任务状态:已暂停this.state = DownloadState.PAUSE// 发送通知this.publishDownloadNotification()}open() {promptAction.showToast({message: '功能未实现'})}publishDownloadNotification(){// 1.判断当前系统是否支持进度条模板if(!this.isSupport){// 当前系统不支持进度条模板return}// 2.准备进度条模板的参数let template = {name: 'downloadTemplate', // 模板名称,必须是downloadTemplatedata: {progressValue: this.progressValue, // 进度条当前进度progressMaxValue: this.progressMaxValue // 进度条的最大值}}let request: notify.NotificationRequest = {id: this.notificationId,template: template,content: {contentType: notify.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT,normal: {title: this.filename + ':  ' + this.state,text: '',additionalText: this.progressValue + '%'}}}// 3.发送通知notify.publish(request).then(() => console.log('test', '通知发送成功')).catch(reason => console.log('test', '通知发送失败!', JSON.stringify(reason)))}
}@Extend(Button) function downloadButton() {.width(75).height(28).fontSize(14)
}

最终呈现的效果如下:

通知意图

我们可以给通知或者其中的按钮设置的行为意图(Want),从而实现拉起应用组件或发布公共事件的能力,下面是其实现的步骤:

// 创建wantInfo信息
let wantInfo: wantAgent.WantAgentInfo = {wants: [{deviceId: '', // 设备的idbundleName: 'com.example.myapplication', // 应用唯一标识abilityName: 'EntryAbility', action: '',entities: [], }],requestCode: 0,operationType: wantAgent.OperationType.START_ABILITY,wantAgentFlags: [wantAgent.WantAgentFlags.CONSTANT_FLAG]
}
// 创建wantAgent实例
this.wantAgentInstance = await wantAgent.getWantAgent(wantInfo)
// 通知请求
let request: notify.NotificationRequest = {id: this.notificationId,template: template,wantAgent: this.wantAgentInstance, // 设置通知意图content: {// }
}

通过上面的案例,我们给下载的进度条添加通知意图,让其下载的通知点击后跳转到下载页面,其实现的代码如下:

import notify from '@ohos.notificationManager'
import wantAgent, { WantAgent } from '@ohos.app.ability.wantAgent'
import promptAction from '@ohos.promptAction'enum DownloadState {NOT_BEGIN = '未开始',DOWNLOADING = '下载中',PAUSE = '已暂停',FINISHED = '已完成',
}@Component
export default struct DownloadCard {// 下载进度@State progressValue: number = 0progressMaxValue: number = 100// 任务状态@State state: DownloadState = DownloadState.NOT_BEGIN// 下载的文件名filename: string = '圣诞星.mp4'// 模拟下载的任务的idtaskId: number = -1// 通知idnotificationId: number = 999isSupport: boolean = falsewantAgentInstance: WantAgentasync aboutToAppear(){// 1.判断当前系统是否支持进度条模板this.isSupport = await notify.isSupportTemplate('downloadTemplate')// 2.创建拉取当前应用的行为意图// 2.1.创建wantInfo信息let wantInfo: wantAgent.WantAgentInfo = {wants: [{bundleName: 'com.example.myapplication',abilityName: 'EntryAbility',}],requestCode: 0,operationType: wantAgent.OperationType.START_ABILITY,wantAgentFlags: [wantAgent.WantAgentFlags.CONSTANT_FLAG]}// 2.2.创建wantAgent实例this.wantAgentInstance = await wantAgent.getWantAgent(wantInfo)}build() {Row({ space: 10 }) {Image($r('app.media.ic_files_video')).width(50)Column({ space: 5 }) {Row() {Text(this.filename)Text(`${this.progressValue}%`).fontColor('#c1c2c1')}.width('100%').justifyContent(FlexAlign.SpaceBetween)Progress({value: this.progressValue,total: this.progressMaxValue,})Row({ space: 5 }) {Text(`${(this.progressValue * 0.43).toFixed(2)}MB`).fontSize(14).fontColor('#c1c2c1')Blank()if (this.state === DownloadState.NOT_BEGIN) {Button('开始').downloadButton().onClick(() => this.download())} else if (this.state === DownloadState.DOWNLOADING) {Button('取消').downloadButton().backgroundColor('#d1d2d3').onClick(() => this.cancel())Button('暂停').downloadButton().onClick(() => this.pause())} else if (this.state === DownloadState.PAUSE) {Button('取消').downloadButton().backgroundColor('#d1d2d3').onClick(() => this.cancel())Button('继续').downloadButton().onClick(() => this.download())} else {Button('打开').downloadButton().onClick(() => this.open())}}.width('100%')}.layoutWeight(1)}.width('100%').borderRadius(20).padding(15).backgroundColor(Color.White)}cancel() {// 取消定时任务if(this.taskId > 0){clearInterval(this.taskId);this.taskId = -1}// 清理下载任务进度this.progressValue = 0// 标记任务状态:未开始this.state = DownloadState.NOT_BEGIN// 取消通知notify.cancel(this.notificationId)}download() {// 清理旧任务if(this.taskId > 0){clearInterval(this.taskId);}// 开启定时任务,模拟下载this.taskId = setInterval(() => {// 判断任务进度是否达到100if(this.progressValue >= 100){// 任务完成了,应该取消定时任务clearInterval(this.taskId)this.taskId = -1// 并且标记任务状态为已完成this.state = DownloadState.FINISHED// 发送通知this.publishDownloadNotification()return}// 模拟任务进度变更this.progressValue += 2// 发送通知this.publishDownloadNotification()}, 500)// 标记任务状态:下载中this.state = DownloadState.DOWNLOADING}pause() {// 取消定时任务if(this.taskId > 0){clearInterval(this.taskId);this.taskId = -1}// 标记任务状态:已暂停this.state = DownloadState.PAUSE// 发送通知this.publishDownloadNotification()}open() {promptAction.showToast({message: '功能未实现'})}publishDownloadNotification(){// 1.判断当前系统是否支持进度条模板if(!this.isSupport){// 当前系统不支持进度条模板return}// 2.准备进度条模板的参数let template = {name: 'downloadTemplate', // 模板名称,必须是downloadTemplatedata: {progressValue: this.progressValue, // 进度条当前进度progressMaxValue: this.progressMaxValue // 进度条的最大值}}let request: notify.NotificationRequest = {id: this.notificationId,template: template,wantAgent: this.wantAgentInstance, // 设置通知意图content: {contentType: notify.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT,normal: {title: this.filename + ':  ' + this.state,text: '',additionalText: this.progressValue + '%'}}}// 3.发送通知notify.publish(request).then(() => console.log('test', '通知发送成功')).catch(reason => console.log('test', '通知发送失败!', JSON.stringify(reason)))}
}@Extend(Button) function downloadButton() {.width(75).height(28).fontSize(14)
}

呈现的效果如下:

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/628185.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

adb 常用命令汇总

目录 adb 常用命令 1、显示已连接的设备列表 2、进入设备 3、安装 APK 文件到设备 4、卸载指定包名的应用 5、从设备中复制文件到本地 6、将本地文件复制到设备 7、查看设备日志信息 8、重启设备 9、截取设备屏幕截图 10、屏幕分辨率 11、屏幕密度 12、显示设备的…

Druid连接池报错

网上各种方法都试了,基本都不行,后来改了一下jar包版本,也就是第四点,才解决。 1、druid.properties文件位置 我学的时候说的是任意位置都行,除了web目录下,但是我试的时候必须要放在resources 文件夹下。…

黑马程序员JavaWeb开发|案例:tlias智能学习辅助系统(5)登录认证

指路(1)(2)(3)(4)👇 黑马程序员JavaWeb开发|案例:tlias智能学习辅助系统(1)准备工作、部门管理_tlias智能学习辅助系统的需求分析-CS…

python学习笔记10(选择结构2、循环结构1)

(一)选择结构2 1、if……else……语句 #(1)基本格式 numbereval(input("请输入您的6位中奖号码:")) if number123456:print("恭喜您,中奖了") else:print("未中奖")#&…

2024美赛数学建模思路 - 案例:FPTree-频繁模式树算法

文章目录 算法介绍FP树表示法构建FP树实现代码 建模资料 ## 赛题思路 (赛题出来以后第一时间在CSDN分享) https://blog.csdn.net/dc_sinor?typeblog 算法介绍 FP-Tree算法全称是FrequentPattern Tree算法,就是频繁模式树算法&#xff0c…

深度解析JVM类加载器与双亲委派模型

概述 Java虚拟机(JVM)是Java程序运行的核心,其中类加载器和双亲委派模型是JVM的重要组成部分。本文将深入讨论这两个概念,并解释它们在实际开发中的应用。 1. 什么是类加载器? 类加载器是JVM的一部分,负…

java-Lambda 语法总结

文章目录 Lambda 语法概览Lambda 表达式语法1.Lambda 表达式与函数接口2.Lambda 遇上 this final Lambda 语法概览 String(] names {”Justi n ”,”caterpillar”,”Bush " }; Arrays . sort (names, new Compara tor<String> () { publ int compare (String na…

pytorch12:GPU加速模型训练

目录 1、CPU与GPU2、数据迁移至GPU2.1 to函数使用方法 3、torch.cuda常用方法4、多GPU并行运算4.1 torch.nn.DataParallel4.2 torch.distributed加速并行训练 5、gpu总结 往期回顾 pytorch01&#xff1a;概念、张量操作、线性回归与逻辑回归 pytorch02&#xff1a;数据读取Data…

WordPress企业模板

首页大图wordpress外贸企业模板 橙色的wordpress企业模板 演示 https://www.zhanyes.com/waimao/6250.html

【算法Hot100系列】全排列

💝💝💝欢迎来到我的博客,很高兴能够在这里和您见面!希望您在这里可以感受到一份轻松愉快的氛围,不仅可以获得有趣的内容和知识,也可以畅所欲言、分享您的想法和见解。 推荐:kwan 的首页,持续学习,不断总结,共同进步,活到老学到老导航 檀越剑指大厂系列:全面总结 jav…

【学习iOS高质量开发】——熟悉Objective-C

文章目录 一、Objective-C的起源1.OC和其它面向对象语言2.OC和C语言3.要点 二、在类的头文件中尽量少引用其他头文件1.OC的文件2.向前声明的好处3.如何正确引入头文件4.要点 三、多用字面量语法&#xff0c;少用与之等价的方法1.何为字面量语法2.字面数值3.字面量数组4.字面量字…

vivado IP使用

使用IP源 注意&#xff1a;有关IP的更多信息&#xff0c;包括添加、打包、模拟和升级IP&#xff0c;请参阅VivadoDesign Suite用户指南&#xff1a;使用IP&#xff08;UG896&#xff09;进行设计。在Vivado IDE中&#xff0c;您可以在RTL项目中添加和管理以下类型的IP核心&…

高通sm7250与765G芯片是什么关系?(一百八十一)

简介&#xff1a; CSDN博客专家&#xff0c;专注Android/Linux系统&#xff0c;分享多mic语音方案、音视频、编解码等技术&#xff0c;与大家一起成长&#xff01; 优质专栏&#xff1a;Audio工程师进阶系列【原创干货持续更新中……】&#x1f680; 优质专栏&#xff1a;多媒…

HTML--CSS--边框、列表、表格样式

边框样式 属性&#xff1a; border-width 边框宽度 border-style 边框外观 border-color 边框颜色 需要同时设定三个属性 border-width 边框宽度 取值为像素值 border-style 边框样式 none 无样式 dashed 虚线 solid 实线 border-color 边框颜色 如示例&#xff1a; 为div设…

Spring Boot框架中Controller层API接口如何支持使用多个@RequestBody注解接受请求体参数

一、前言 众所周知&#xff0c;在Spring Boot框架中&#xff0c;Controller层API接口编码获取请求体参数时&#xff0c;在参数上会使用RequestBody注解&#xff1b;如果一次请求中&#xff0c;请求体参数携带的内容需要用多个参数接收时&#xff0c;能不能多次使用RequestBody…

跟我学java|Stream流式编程——并行流

什么是并行流 并行流是 Java 8 Stream API 中的一个特性。它可以将一个流的操作在多个线程上并行执行&#xff0c;以提高处理大量数据时的性能。 在传统的顺序流中&#xff0c;所有的操作都是在单个线程上按照顺序执行的。而并行流则会将流的元素分成多个小块&#xff0c;并在多…

微信小程序 全局配置||微信小程序 页面配置||微信小程序 sitemap配置

全局配置 小程序根目录下的 app.json 文件用来对微信小程序进行全局配置&#xff0c;决定页面文件的路径、窗口表现、设置网络超时时间、设置多 tab 等。 以下是一个包含了部分常用配置选项的 app.json &#xff1a; {"pages": ["pages/index/index",&q…

十五.流程控制与游标

流程控制与游标 1.流程控制1.1分支结构之IF1.2分支结构值CASE1.3循环结构之LOOP1.4循环结构之WHILE1.5循环结构之REPEAT1.6跳转语句之LEAVE语句1.7跳转语句之ITERATE语句 2.游标2.1什么是游标2.2使用游标步骤4.3举例4.5小结 1.流程控制 解决复杂问题不可能通过一个 SQL 语句完…

C# Winform翻牌子记忆小游戏

效果 源码 新建一个winform项目命名为Matching Game&#xff0c;选用.net core 6框架 并把Form1.cs代码修改为 using Timer System.Windows.Forms.Timer;namespace Matching_Game {public partial class Form1 : Form{private const int row 4;private const int col 4;p…

简单介绍JDK、JRE、JVM三者区别

简单介绍JDK vs JRE vs JVM三者区别 文编|JavaBuild 哈喽&#xff0c;大家好呀&#xff01;我是JavaBuild&#xff0c;以后可以喊我鸟哥&#xff0c;嘿嘿&#xff01;俺滴座右铭是不在沉默中爆发&#xff0c;就在沉默中灭亡&#xff0c;一起加油学习&#xff0c;珍惜现在来之不…