给应用添加通知消息
通知介绍
通知旨在让用户以合适的方式及时获得有用的新消息,帮助用户高效地处理任务。应用可以通过通知接口发送通知消息,用户可以通过通知栏查看通知内容,也可以点击通知来打开应用,通知主要有以下使用场景:
- 显示接收到的短消息、即时消息等。
- 显示应用的推送消息,如广告、版本更新等。
- 显示当前正在进行的事件,如下载等。
通知表现形式
通知会在不同场景以不同形式提示用户,例如通知在状态栏上显示为图标、在通知栏上回显示通知详细信息。重要的信息还可以使用横幅通知,浮动在界面顶部显示。
通知结构
下面以基础的文本通知为例,介绍通知的基本结构。
- 通知小图标:表示通知的功能与类型。
- 通知名称:应用名称或功能名称。
- 时间:发送通知的时间,系统默认显示。
- 展开箭头:点击标题区,展开被折叠的内容和按钮。若无折叠的内容和按钮,不显示此箭头。
- 内容标题:描述简明概要。
- 内容详情:描述具体内容或详情。
创建通知
本节将介绍几种常见类型通知的创建,在创建通知前需要先导入notificationManager模块,该模块提供通知管理的能力,包括发布、取消发布通知,创建、获取、移除通知通道等能力。
import { notificationManager } from '@kit.NotificationKit';
发布基础类型通知
基础类型通知主要应用于发送短信息、提示信息、广告推送等,支持普通文本类型、长文本类型、多行文本类型,可以通过ContentType指定通知的内容类型。下面以普通文本类型为例来介绍基础通知的发布,其他基础类型您可以查阅API。
- 发布普通文本类型通知,需要设置ContentType类型为
ContentType.NOTIFICATION_CONTENT_BASIC_TEXT
。
@Entry
@Component
struct NotificationDemo {
publishNotification() {
let notificationRequest: notificationManager.NotificationRequest = {
id: 1,
content: {
notificationContentType: notificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT,
normal: {
title: '通知内容标题',
text: '通知内容详情'
}
}
}
}
notificationManager.publish(notificationRequest).then(() => {
console.info('publish success');
}).catch((err: Error) => {
console.error(`publish failed,message is ${err}`);
})
build() {
Column() {
Button("发送通知")
.onClick(() => {
this.publishNotification()
})
}
.width("100%")
}
}
效果图如下:
发布进度类型通知
进度条通知也是常见的通知类型,主要应用于文件下载、事务处理进度显示。目前系统模板仅支持进度条模板,效果示意如下图所示:
在发布进度类型通知前需要查询系统是否支持进度条模板。
notificationManager.isSupportTemplate('downlaodTemplate').then(isSupport => {
if(!isSupport) {
promptAction.showToast({
message:$r('app.string.invalid_button_toast')
})
}
this.isSupport = isSupport
});
构造进度条模板,name字段当前需要固定配置为downloadTemplate。
let template: notificationManager.NotificationTemplate = {
name: 'downloadTemplate',
data: {
// 当前进度值
progressValue: progress,
// 最大进度值
progressMaxValue: 100
}
}
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}`);
})
更新通知
在发出通知后,使用您之前使用的相同通知ID,再次调用notificationManager.publish来实现通知的更新。如果之前的通知是关闭的,将会创建新通知。
移除通知
- 通过通知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.OTHER_TYPES:其他类型,状态栏中不显示通知图标,且没有横幅或提示音。
创建通知组
将不同类型的通知分为不同的组,以便用户可以更好的管理他们。当同组的通知有多条的时候,会自动折叠起来,避免通知比较多的时候,通知界面比较杂乱,例如当通知栏里有聊天消息通知和商品推荐通知时,我们只需要通过设置字段groupName,就可以对通知进行分组,给groupName设置不同的值可以将通知分为不同的组。
您可以使用groupName来指定通知组来实现,示例代码如下:
let notifyId = 0;
let chatRequest: notificationManager.NotificationRequest = {
id: notifyId++,
groupName: 'ChatGroup',
content: {
// ...
}
};
let productRequest: notificationManager.NotificationRequest = {
id: notifyId++;
groupName: 'ProductGroup',
content: {
// ...
}
}
为通知添加行为意图
WantAgent提供了封装行为意图的能力,这里所说的行为意图主要是指拉起指定的应用组件及发布公共事件等能力。给通知添加行为意图后,点击通知后可以拉起指定的UIAbility或者发布公共事件,可以按照以下步骤来实现:
- 导入模块
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: [
// 设置事件名
actions: 'event_name',
parameters: {},
],
operationType: wantAgent.OperationType.SEND_COMMON_EVENT,
requestCode: 100,
wantAgentFlags: [ wantAgent.WantAgentFlags.CONSTANT_FLAG],
}
- 创建WantAgent对象。
let wantAgentObj = null;
wantAgent.getWantAgent(wantAgentInfo)
.then((data) => {
wantAgentObj = data;
})
.catch((err: Error) => {
console.error(`get wantAgent failed because ${JSON.stringify(err)}`);
})
- 构造NotificationRequest对象。
let notificationRequest: notificationManager.NotificationRequest = {
id: 1,
content: {
notificationContetnType: notificationManger.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT,
normal: {
title: "通知标题",
text: "通知内容"
}
},
wantAgent: wantAgentObj
}
- 发布WantAgent通知。
notificationManager.public(notificationRequest).then(() => { // 发布通知
console.info("publish success");
}).catch((err: Error) => {
console.error(`publish failed, code is ${err.code}, message is ${err.message}`);
});
用户通过点击通知栏上的通知,即可触发WantAgent的动作。
参考链接
- WantAgent的使用更多API可以参考:WantAgent模块。
- 关于通知模块更多API的使用可以参考:NotificationManager模块。
后台代理提醒
简介
应用在可能需要在指定的时刻,向用户发送一些业务提醒通知。例如购物类应用,希望在指定时间点提醒用户有优惠活动。为满足此类业务诉求,HarmonyOS提供后台代理提醒功能,在应用退居后台或退出后,计时和提醒通知功能被系统后台代理接管。
后台代理提醒业务类型:
- 倒计时类:基于倒计时的提醒功能,适用于短时的计时提醒业务。
- 日历类:基于日历的提醒功能,适用于较长时间的提醒业务。
- 闹钟类:基于时钟的提醒功能,适用于指定时刻的提醒业务。
后台代理提醒是由系统后台进程代理应用的提醒功能。后台代理提醒服务通过reminderAgentManager
模块提供提醒定义、创建提醒、取消提醒等能力。
后台代理提醒服务提供统一的提升管理能力,在应用退居后台或退出后,计时和提醒通知功能呗系统后台代理接管。
以新增一个9点的喝水提醒为例:
假设用户在8点新增这个喝水提醒,应用根据用户设置的信息生成提醒实例并发布提醒。由后台代理提醒服务调用系统服务启动计时。
到9点时,系统唤醒后台代理提醒服务发布通知,最终由通知服务触发桌面显示通知。
在整个流程中,应用权限:
- 使用
reminderAgentManager
模块的ReminderRequest
类定义提醒实例; - 使用
reminderAgentManager
模块的publishReminder
接口发布提醒。
无需关注计时和通知发布等功能如何实现。
若是删除提醒流程,需要使用reminderAgentManager
模块的cancelReminder
接口取消提醒;若是修改提醒流程,则需要先删除旧的提醒,在新增新的提醒。
给应用添加提醒
以闹钟应用为例,实现提醒功能有以下前置条件:
- 添加后台代理提醒
"module": {
//..
"requestPermissions":[
{
"name":"ohos.permission.PUBLISH_AGENT_REMINDER"
}
]
}
- 导入后台代理提醒
reminderAgentManager
模块
import { reminderAgentManager } from '@kit.BackgroundTasksKit';
如果是新增提醒,实现步骤如下:
- 用
reminderAgent.ReminderRequest
类定义提醒实例。
import { reminderAgentManager } from '@kit.BackgroundTaskKit'
export class ReminderService {
public addReminder(alarmItem: ReminderItem, callback?: (reminderId: number)=>void) {
let reminder = this.initReminder(alarmItem);
reminderAgentManager.publishReminder(reminder,(err, reminderId)=>{
if( callback != null) {
callback(reminderId);
}
})
}
private initReminder(item: ReminderItem): reminderAgentManager.ReminderRequestAlarm {
return {
reminderType: item.remindType,
hour:item.hour,
minute:item.minute,
daysOfWeek: item.rpeatDays,
title:item.name,
ringDuration: item.duartion * CommonConstants.DEFAULT_TOTAL_MINUTE,
snoozeTimes: item.intervalTimes,
timeInterval: item.intervalMinute * CommonConstants.DEFAULT_TOTAL_MINUTE,
actionButton: [
{
title: '关闭',
type: reminderAgentManager.ActionButtonType.ACTION_BUTTON_TYPE_CLOSE
}
],
wantAgent: {
pkgName: CommonConstants.BUNDLE_NAME,
abilityName: CommonConstants.ABILITY_NAME
},
notificationId: item.notificationId,
// ...
}
}
}
- 发布提醒。
import { reminderAgentManager } from '@kit.BackgroundTaskKit'
//..
export class ReminderService {
public addReminder(alarmItem: ReminderItem, callback?: (reminderId) => void) {
let reminder = this.initReminder(alarmItem);
reminderAgentManager.publishReminder(reminder, (err,reminderId) => {
if(callback != null) {
callback(reminderId);
}
});
}
private initReminder(item: ReminderItem): reminderAgentManager.ReminderRequestAlarm {
// ...
}
// ...
}
如果需要修改提醒,则需要先进行旧提醒的删除,再新增新的提醒。
public async setAlarmRemind(alarmItem: AlarmItem) {
let index: number = await this.findAlarmWithId(alarmItem.id);
if (index !== CommonConstants.DEFAULT_NUMBER_NEGATIVE) {
this.reminderService.deleteReminder(alarmItem.id);
} else {
// ...
}
this.reminderService.addReminder(alarmItem,(newId: number) => {
alarmItem.id = newId;
})
}
参考
更多后台代理提醒场景和相关知识请参考开发指南和API参考: