HarmonyOS开发(十):通知和提醒

1、通知概述

1.1、简介

应用可以通过通知接口发送通知消息,终端用户可以通过通知栏查看通知内容,也可以点击通知来打开应用。

通知使用的的常见场景:

  • 显示接收到的短消息、即使消息...
  • 显示应用推送消息
  • 显示当前正在进行的事件,如下载等

HarmonyOS通过ANS(Advanced Notification Service,通知系统服务)对通知消息进行管理,支持多种通知类型。

1.2、通知的业务流程

业务流程中由通知子系统、通知发送端、通知订阅组件

一条通知从通知发送端产生,发送到通知子系统,然后再由通知子系统分发给通知订阅端。

1.3、通知消息的表现形式

 1.4、通知结构

1、通知小图图标:表示通知的功能与类型

2、通知名称:应用名称或者功能名称

3、时间:发送通知的时间,系统默认显示

4、展示图标:用来展开被折叠的内容和按钮,如果没有折叠的内容和按钮,则不显示这个图标

5、内容标题

6、内容详情

2、基础类型通知

基础类型通知主要应用于发送短信息、提示信息、广告推送...,它支持普通文本类型、长文本类型、图片类型。

普通文本类型                NOTIFICATION_CONTENT_BASIC_TEXT

长文本类型                    NOTIFICATION_CONTENT_LONG_TEXT

多行文本类型                NOTIFICATION_CONTENT_MULTILINE

图片类型                       NOTIFICATION_CONTENT_PICTURE

2.1、相关接口

接口名描述
publish(request:NotificatioinRequest,callback:AsyncCallback<void>):void发布通知
cancel(id:number,label:string,callback:AsyncCallback<void>):void取消指定的通知,通过id来判断是哪个通知
cancelAll(callback:AsycCallback<void>):void取消所有该应用发布的通知

2.2、开发步骤

1、导入模块

import NotificationManager from '@ohos.notificationManager';

2、构造NotificationRequest对象,发布通知

import notificationManager from '@ohos.notificationManager'
import Prompt from '@system.prompt'
import image from '@ohos.multimedia.image';@Entry
@Component
struct Index {publishNotification() {let notificationRequest: notificationManager.NotificationRequest = {id: 0,slotType: notificationManager.SlotType.SERVICE_INFORMATION,content: {contentType: notificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT,normal:{title: '通知标题',text: '这是一个通知的消息内容',additionalText: '通知附加内容'  // 附加内容是对通知内容的补充}}};notificationManager.publish(notificationRequest).then(() => {// 发布通知Prompt.showToast({message: '发布通知消息成功',duration: 2000})}).catch((err) => {Prompt.showToast({message: `发布通知失败,失败代码:${err.code},失败原因:${err.message}`,duration: 2000})});}/* 多行文本通知 */publicNotification1(){let notificationRequest:notificationManager.NotificationRequest = {id: 1,content: {contentType: notificationManager.ContentType.NOTIFICATION_CONTENT_MULTILINE,multiLine: {title: '通知标题',text: '通知的内容简介',briefText: 'briefText内容',longTitle: 'longTitle内容',lines: ['第一行内容','第二行内容','第三行内容']}}};notificationManager.publish(notificationRequest).then(() => {// 发布通知Prompt.showToast({message: '发布通知消息成功',duration: 2000})}).catch((err) => {Prompt.showToast({message: `发布通知失败,失败代码:${err.code},失败原因:${err.message}`,duration: 2000})});}/* 图片通知 */async publishPictureNotification(){// 把资源图片转为PixelMap对象let resourceManager = getContext(this).resourceManager;let imageArray = await resourceManager.getMediaContent($r('app.media.image2').id);let imageResource = image.createImageSource(imageArray.buffer);let pixelMap = await imageResource.createPixelMap();// 描述通知信息let notificationRequest:notificationManager.NotificationRequest = {id: 2,content: {contentType: notificationManager.ContentType.NOTIFICATION_CONTENT_PICTURE,picture: {title: '通知消息的标题',text: '展开查看详情,通知内容',expandedTitle: '展开时的内容标题',briefText: '这里是通知的概要内容,对通知的总结',picture: pixelMap}}};notificationManager.publish(notificationRequest).then(() => {// 发布通知消息Prompt.showToast({message: '发布通知消息成功',duration: 2000})}).catch((err) => {Prompt.showToast({message: `发布通知失败,失败代码:${err.code},失败原因:${err.message}`,duration: 2000})});}build() {Row() {Column() {Button('发送通知').width('50%').margin({bottom:10}).onClick(() => {this.publishNotification()})Button('发送多行文本通知').width('50%').margin({bottom:10}).onClick(() => {this.publicNotification1()})Button('发送图片通知').width('50%').margin({bottom:10}).onClick(() => {this.publishPictureNotification()})}.width('100%')}.height('100%')}
}

3、进度条类型通知

进度条通知也是常见的通知类型,主要应用于文件下载、事务处理进度的显示。

HarmonyOS提供了进度条模板,发布通知应用设置好进度条模板的属性值,通过通知子系统发送到通知栏显示。

当前系统模板仅支持进度条模板,通知模板NotificationTemplate中的data参数为用户自定义数据,用来显示模块相关的数据。

3.1、相关接口

isSupportTemplate(templateName: string,callback:AsyncCallback<boolean>) : void        查询模板是否存在

3.2、开发步骤

1、导入模块

import NotificationManager from '@ohos.notificationManager'

2、查询系统是否支持进度条模板

NotificationManager.isSupportTemplate('downloadTemplate').then((data) => {let isSupportTpl: boolean = data;    // 这里为true则表示支持模板// ...
}).catch((err) => {console.error('查询失败')
})

3、在第2步之后,再构造进度条模板对象,发布通知

import notificationManager from '@ohos.notificationManager'
import Prompt from '@system.prompt'@Entry
@Component
struct ProgressNotice {async publishProgressNotification() {let isSupportTpl: boolean;await notificationManager.isSupportTemplate('downloadTemplate').then((data) => {isSupportTpl = data;}).catch((err) => {Prompt.showToast({message: `判断是否支持进度条模板时报错,error[${err}]`,duration: 2000})})if(isSupportTpl) {// 构造模板let template = {name: 'downloadTemplate',data: {progressValue: 60, // 当前进度值progressMaxValue: 100 // 最大进度值}};let notificationRequest: notificationManager.NotificationRequest = {// id: 100, // 这里的id可以不传content : {contentType: notificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT,normal: {title: '文件下载:鸿蒙学习手册.pdf',text: '下载进度',additionalText: '60%'}},template: template};// 发布通知notificationManager.publish(notificationRequest).then(() => {Prompt.showToast({message: `发布通知成功!`,duration: 2000})}).catch((err) => {Prompt.showToast({message: `发布通知失败,error[${err}]`,duration: 2000})})} else {Prompt.showToast({message: '不支持downloadTemplate进度条通知模板',duration: 2000})}}build() {Row() {Column() {Button('发送进度条通知').width('50%').onClick(()=>{this.publishProgressNotification()})}.width('100%')}.height('100%')}
}

4、通知其它配置

4.1、设置通道通知

设置通道知,可以让通知有不同的表现形式,如社交类型的通知是横幅显示的,并且有提示音。但一般的通知则不会横幅显示,可以使用slotType来实现。

  • SlotType.SOCIAL_COMMUNICATION:社交 类型,状态栏中显示通知图标,有横幅提示音
  • SlotType.SERVICE_INFORMATION:服务类型,在状态栏中显示通知图标,没有横幅但有提示音
  • SlotType.CONTENT_INFORMATION:内容类型,状态栏中显示通知图标,没有横幅和提示音
  • SlotType.OTHER_TYPE:其它类型,状态栏中不显示通知图标,没有横幅和提示音
import image from '@ohos.multimedia.image';
import notificationManager from '@ohos.notificationManager';
import Prompt from '@system.prompt';
@Entry
@Component
struct SlotTypeTest {async publishSlotTypeNotification(){let imageArray = await getContext(this).resourceManager.getMediaContent($r('app.media.tx').id);let imageResource = image.createImageSource(imageArray.buffer);let opts = {desiredSize: {height: 72, width: 72}};let largePixelMap = await imageResource.createPixelMap(opts);let notificationRequest: notificationManager.NotificationRequest = {id: 1,content: {contentType: notificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT,normal:{title: '赵子龙',text: '等会大战三百回合~~'}},slotType:notificationManager.SlotType.SOCIAL_COMMUNICATION,largeIcon: largePixelMap  // 通知大图标};notificationManager.publish(notificationRequest).then(() => {// 发布通知Prompt.showToast({message: '发布通知消息成功',duration: 2000})}).catch((err) => {Prompt.showToast({message: `发布通知失败,失败代码:${err.code},失败原因:${err.message}`,duration: 2000})});}build() {Row() {Column() {Button('发送通知').width('50%').onClick(() => {this.publishSlotTypeNotification()})}.width('100%')}.height('100%')}
}

5、为通知添加行为意图

WantAgent提供了封装行为意图的能力,这里的行为意图能力就要是指拉起指定的应用组件及发布公共事件等能力。

HarmonyOS支持以通知的形式,把WantAgent从发布方传递到接收方,从而在接收方触发WantAgent中指定的意图。

为通知添加行为意图的实现方式如上图所示,发布通知的应用向组件管理服务AMS(Ability Manager Service)申请WantAgent,然后随其他通知信息 一起发送给桌面,当用户在桌面通知栏上点击通知时,触发WantAgent动作。

5.1、相关接口

接口名描述
getWantAgent(info: WantAgentInfo, callback:AsyncCallback<WantAgent>):void创建WantAgent
trigger(agent:WantAgent, triggerInfo:TrggerInfo,callback?:Callback<CompleteData>):void触发WantAgent意图
cancel(agent:WantAgent,callback:AsyncCallback<void>):void取消WantAgent
getWant(agent:WantAgent,callback:AsyncCallback<Want>):void获取WantAgent的want
equal(agent:WantAgent,otherAgent:WantAgent,callback:AsyncCallback<boolean>):void判断两个WantAgent实例是否相等

5.2、开发步骤

1、导入模块

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

2、发送通知

import notificationManager from '@ohos.notificationManager'
import wantAgent from '@ohos.wantAgent';
import Prompt from '@system.prompt';let wantAgentObj = null;  // 保存创建成功的wantAgent对象,后续使用其完成触发的动作
// 通过WantAgentInfo的operationType设置动作类型
let wantAgentInfo = {wants: [{deviceId: '', // 这里为空表示是本设备bundleName: 'com.xiaoxie', // 在app.json5中查找// moduleName: 'entry', // 在module.json5中查找,如果待启动的ability在同一个module则可以不写abilityName: 'MyAbility', // 待启动ability的名称,在module.json5中查找}],operationType: wantAgent.OperationType.START_ABILITY,requestCode: 0,wantAgentFlags:[wantAgent.WantAgentFlags.CONSTANT_FLAG]
}@Entry
@Component
struct ButtonNotice {async publishButtonNotice(){// 创建WantAgentawait wantAgent.getWantAgent(wantAgentInfo).then((data) => {wantAgentObj = data;}).catch((err) => {Prompt.showToast({message: `创建wangAgent失败,${JSON.stringify(err)}`})})let notificationRequest:notificationManager.NotificationRequest = {id: 1,slotType: notificationManager.SlotType.SOCIAL_COMMUNICATION,  // 这个是社交类型的通知content: {contentType: notificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT,normal: {title: '赵子龙',text: '吃饭了吗?'}},actionButtons: [{title: '回复',wantAgent: wantAgentObj}]};// 发布WantAgent通知notificationManager.publish(notificationRequest,(err) => {if(err) {Prompt.showToast({message: '发布通知失败!',duration: 2000})} else {Prompt.showToast({message: '发布通知成功!',duration: 2000})}})}build() {Row() {Column() {Button('发送通知').width('50%').onClick(() => {this.publishButtonNotice()})}.width('100%')}.height('100%')}
}

6、后台代理提醒

当应用需要在指定时刻向用户发送一些业务提醒通知时,HarmonyOS提供后台代理提醒功能,在应用退居后台或退出后,计时和提醒通知功能被系统后台代理接管。

后台代理提醒业务类型:

1、倒计时类:基于倒计时的提醒功能,适用于短时的计时提醒业务

2、日历类:基于日历的提醒功能,适用于较长时间的提醒业务

3、闹钟类:基于时钟的提醒功能,适用于指定时刻的提醒业务

后台代理提醒就是由系统后台进程代理应用的提醒功能。后台代理提醒服务通过reminderAgentManager模块提醒定义、创建提醒、取消提醒...

 提醒使用的前置条件

1、添加后台代理提醒的使用权限:ohos.permission.PUBLISH_AGENT_REMINDER

2、导入后台代理提醒reminderAgentManager模块

import reminderAgent from '@ohos.reminderAgentManager';
import reminderAgent from '@ohos.reminderAgentManager';
import Prompt from '@system.prompt';@Entry
@Component
struct ReminderTest {@State message: string = 'Hello World';reminderId:number;myReminderAgent(){let reminderRequest:reminderAgent.ReminderRequestAlarm = {reminderType: reminderAgent.ReminderType.REMINDER_TYPE_ALARM,hour: 12,minute: 23,daysOfWeek: [1,2,3,4,5,6,7],  // 星期1~7title: '提醒信息 title',ringDuration: 10, // 响铃时长snoozeTimes: 1, // 延迟提醒次数,默认是0timeInterval: 60*60*5,  // 延迟提醒间隔时间actionButton: [{title: '关闭',type: reminderAgent.ActionButtonType.ACTION_BUTTON_TYPE_CLOSE}]/*,wantAgent: { // 提醒到达时自动拉起的目标abilitypkgName: 'com.xiaoxie',abilityName: 'MyAbility'}*/};reminderAgent.publishReminder(reminderRequest,(err,reminderId) => {if(err) {Prompt.showToast({message: '发布提醒失败',duration: 2000})return;}Prompt.showToast({message: '发布提醒成功!id = ' + reminderId,duration: 2000})this.reminderId = reminderId;})}build() {Row() {Column() {Text(this.message).fontSize(20).fontWeight(FontWeight.Bold).margin({bottom:15})Button('发布提醒').width('50%').onClick(() => {this.myReminderAgent()})}.width('100%')}.height('100%')}
}

此处提醒没有成功,暂未确认到具体原因 !!!等更新!!!

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

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

相关文章

Unity UGUI TextMeshPro实现输入中文和表情包(Emoji)表情

目录 实现中文显示 准备工作 1、打开Window——TextMeshPro——FontAssetCreator 2、把字体文件放入SourceFont中 3、把CharacterSet改为Characters from File 4、把字体库文件放入Characters File 5、设置好参数点击Generate Font Atlas等待完成后保存 6、把生成后保存…

洗鞋机行业分析:2023年市场发展前景及消费现状

随着消费主力的转移&#xff0c;年轻群体在消费中的话语权和影响力越来越大&#xff0c;“精致懒”正在成为潮流。洗鞋机作为消费升级时代的产物&#xff0c;自诞生以来&#xff0c;经过十几年的发展&#xff0c;逐渐被年轻消费者熟知&#xff0c;洗鞋机品牌阵营和产品种类也变…

Redis——某马点评day02——商铺缓存

什么是缓存 添加Redis缓存 添加商铺缓存 Controller层中 /*** 根据id查询商铺信息* param id 商铺id* return 商铺详情数据*/GetMapping("/{id}")public Result queryShopById(PathVariable("id") Long id) {return shopService.queryById(id);} Service…

域名证书(SSL)申请

获取域名证书的步骤如下&#xff1a; 选择认证机构&#xff1a;域名证书必须从受信任的认证机构中申请&#xff0c;如JoySSL、GeoTrust、Thawte等。收集信息&#xff1a;在申请域名证书之前&#xff0c;需要准备一些证明信息&#xff0c;如域名认证、身份证明等。创建CSR&…

C //例10.4 从键盘输入10个学生的有关数据,然后把它们转存到磁盘文件上去。

C程序设计 &#xff08;第四版&#xff09; 谭浩强 例10.4 例10.4 从键盘输入10个学生的有关数据&#xff0c;然后把它们转存到磁盘文件上去。 IDE工具&#xff1a;VS2010 Note: 使用不同的IDE工具可能有部分差异。 代码块 方法&#xff1a;使用指针&#xff0c;函数的模块…

一次显著的性能提升,从8s到0.7s

前言 最近我在公司优化了一些慢查询SQL&#xff0c;积累了一些SOL调优的实战经验。 这篇文章从实战的角度出发&#xff0c;给大家分享一下如何做SQL调优。 经过两次优化之后&#xff0c;慢SQL的性能显著提升了&#xff0c;耗时从8s优化到了0.7s。 现在拿出来给大家分享一下…

老老实实的程序员该如何描述自己的缺点

答辩的时候&#xff0c;晋升的时候&#xff0c;面试的时候&#xff0c;你有没有经常遇到一个问题&#xff0c;那就是你觉得自己有什么缺点吗&#xff1f; 目录 1. 每个人都有缺点 2. 这道题在考什么&#xff1f; 3. 我之前是怎么回答的 4. 你可以这样回答试一试 5. 总结 …

ECharts的颜色渐变

目录 一、直接配置参数实现颜色渐变 二、使用ECharts自带的方法实现颜色渐变 一、两种渐变的实现方法 1、直接配置参数实现颜色渐变 横向的渐变&#xff1a; //主要代码 option {xAxis: {type: category,boundaryGap: false,data: [Mon, Tue, Wed, Thu, Fri, Sat, Sun]},yA…

路径规划之PRM算法

系列文章目录 路径规划之Dijkstra算法 路径规划之Best-First Search算法 路径规划之A *算法 路径规划之D *算法 路径规划之PRM算法 路径规划之PRM算法 系列文章目录前言一、前期准备1.栅格地图2.采样3.路标 二、PRM算法1.起源2.流程3. 优缺点4. 实际效果 前言 之前提到的几种…

如何解决el-table中动态添加固定列时出现的行错位

问题描述 在使用el-table组件时&#xff0c;我们有时需要根据用户的操作动态地添加或删除一些固定列&#xff0c;例如操作列或选择列。但是&#xff0c;当我们使用v-if指令来控制固定列的显示或隐藏时&#xff0c;可能会出现表格的行错位的问题&#xff0c;即固定列和非固定列…

【Unity动画】Sprite 2D精灵创建编辑到动画

如何切图&#xff08;sprite editor&#xff09; 有时候一张图可能包含了很多张子图&#xff0c;就需要在Unity 临时处理一下&#xff0c;切开&#xff0c;比如动画序列帧图集 虽然我们可以在PS里面逐个切成一样的尺寸导出多张&#xff0c;再放回Unity&#xff0c;但是不需要这…

深入理解数据在内存中是如何存储的,位移操作符如何使用(能看懂文字就能明白系列)文章超长,慢慢品尝

系列文章目录 C语言笔记专栏 能看懂文字就能明白系列 &#x1f31f; 个人主页&#xff1a;古德猫宁- &#x1f308; 信念如阳光&#xff0c;照亮前行的每一步 文章目录 系列文章目录&#x1f308; *信念如阳光&#xff0c;照亮前行的每一步* 前言引子一、2进制和进制转化为什么…