大约 6 分钟
基础通知
https://developer.huawei.com/consumer/cn/doc/harmonyos-guides-V3/notification-guidelines-0000001281360946-V3


https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V3/js-apis-notification-0000001333321097-V3
名称 | 值 | 说明 |
---|---|---|
NOTIFICATION_CONTENT_BASIC_TEXT | ContentType | 普通类型通知。 |
NOTIFICATION_CONTENT_LONG_TEXT | ContentType | 长文本类型通知。 |
NOTIFICATION_CONTENT_PICTURE | ContentType | 图片类型通知。 |
NOTIFICATION_CONTENT_CONVERSATION | ContentType | 社交类型通知。 |
NOTIFICATION_CONTENT_MULTILINE | ContentType | 多行文本类型通知。 |
系统能力:以下各项对应的系统能力均为SystemCapability.Notification.Notification
名称 | 可读 | 可写 | 类型 | 必填 | 描述 |
---|---|---|---|---|---|
content | 是 | 是 | NotificationContent | 是 | 通知内容。 |
id | 是 | 是 | number | 否 | 通知ID。 |
slotType | 是 | 是 | SlotType | 否 | 通道类型。 |
isOngoing | 是 | 是 | boolean | 否 | 是否进行时通知。 |
isUnremovable | 是 | 是 | boolean | 否 | 是否可移除。 |
deliveryTime | 是 | 是 | number | 否 | 通知发送时间。 |
tapDismissed | 是 | 是 | boolean | 否 | 通知是否自动清除。 |
autoDeletedTime | 是 | 是 | number | 否 | 自动清除的时间。 |
wantAgent | 是 | 是 | WantAgent | 否 | 点击跳转的WantAgent。 |
extraInfo | 是 | 是 | 否 | 扩展参数。 | |
color | 是 | 是 | number | 否 | 通知背景颜色。 |
colorEnabled | 是 | 是 | boolean | 否 | 通知背景颜色是否使能。 |
isAlertOnce | 是 | 是 | boolean | 否 | 设置是否仅有一次此通知警报。 |
isStopwatch | 是 | 是 | boolean | 否 | 是否显示已用时间。 |
isCountDown | 是 | 是 | boolean | 否 | 是否显示倒计时时间。 |
isFloatingIcon | 是 | 是 | boolean | 否 | 是否显示状态栏图标。 |
label | 是 | 是 | string | 否 | 通知标签。 |
badgeIconStyle | 是 | 是 | number | 否 | 通知角标类型。 |
showDeliveryTime | 是 | 是 | boolean | 否 | 是否显示分发时间。 |
actionButtons | 是 | 是 | Array<NotificationActionButton> | 否 | 通知按钮,最多两个按钮。 |
smallIcon | 是 | 是 | PixelMap | 否 | 通知小图标。 |
largeIcon | 是 | 是 | PixelMap | 否 | 通知大图标。 |
creatorBundleName | 是 | 否 | string | 否 | 创建通知的包名。 |
creatorUid | 是 | 否 | number | 否 | 创建通知的UID。 |
creatorPid | 是 | 否 | number | 否 | 创建通知的PID。 |
creatorUserId8+ | 是 | 否 | number | 否 | 创建通知的UserId。 |
hashCode | 是 | 否 | string | 否 | 通知唯一标识。 |
groupName8+ | 是 | 是 | string | 否 | 组通知名称。 |
template8+ | 是 | 是 | NotificationTemplate | 否 | 通知模板。 |
distributedOption8+ | 是 | 是 | DistributedOptions | 否 | 分布式通知的选项。 |
notificationFlags8+ | 是 | 否 | NotificationFlags | 否 | 获取NotificationFlags。 |



import notify from '@ohos.notificationManager'
import image from '@ohos.multimedia.image'
@Entry
@Component
struct Index {
// 全局任务 id
idx: number = 100
// 图像
pixel: PixelMap
async aboutToAppear() {
// 获取资源管理器
let rm = getContext(this).resourceManager
// 读取图片
let file = await rm.getMediaContent($r('app.media.watchGT4'))
// 创建 PixelMap
image.createImageSource(file.buffer).createPixelMap()
.then(value => this.pixel = value)
.catch(reason => console.error(reason))
}
build() {
Column({ space: 10 }) {
Button(`发送normalText通知`)
.onClick(() => this.publishNormalTextNotification())
Button(`发送longText通知`)
.onClick(() => this.publishLongTextNotification())
Button(`发送multiLine通知`)
.onClick(() => this.publishMultiLineNotification())
Button(`发送Picture通知`)
.onClick(() => this.publishPictureNotification())
}
.width('100%')
}
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)))
}
}
进度条通知

import Notification from '@ohos.notificationManager'
import wantAgent, { WantAgent } from '@ohos.app.ability.wantAgent'
import promptAction from '@ohos.promptAction'
import Prompt from '@system.prompt'
enum DownloadState {
NOT_BEGIN = '未开始',
DOWNLOADING = '下载中',
PAUSE = '已暂停',
FINISHED = '已完成',
}
@Entry
@Component
struct Index {
// 下载进度
@State progressValue: number = 0
progressMaxValue: number = 100
// 任务状态
@State state: DownloadState = DownloadState.NOT_BEGIN
// 下载的文件名
filename: string = '圣诞星.mp4'
// 模拟下载的任务的id
taskId: number = -1
// 通知id
notificationId: number = 999
isSupport: boolean = false
wantAgentInstance: WantAgent
async aboutToAppear() {
// 1.判断当前系统是否支持进度条模板
this.isSupport = await Notification.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
}
console.log(this.notificationId.toString())
// 清理下载任务进度
this.progressValue = 0
// 标记任务状态:未开始
this.state = DownloadState.NOT_BEGIN
// 取消通知
Notification.cancel(this.notificationId).then((response) => {
console.log('ssssss', JSON.stringify(response))
})
}
download() {
// 清理旧任务
if (this.taskId > 0) {
clearInterval(this.taskId);
}
// 开启定时任务,模拟下载
this.taskId = setInterval(() => {
// 判断任务进度是否达到100
if (this.progressValue >= 100) {
// 任务完成了,应该取消定时任务
clearInterval(this.taskId)
this.taskId = -1
// 并且标记任务状态为已完成
this.state = DownloadState.FINISHED
// 发送通知
this.publishProgressNotification()
return
}
// 模拟任务进度变更
this.progressValue += 2
// 发送通知
this.publishProgressNotification()
}, 500)
// 标记任务状态:下载中
this.state = DownloadState.DOWNLOADING
}
pause() {
// 取消定时任务
if (this.taskId > 0) {
clearInterval(this.taskId);
this.taskId = -1
}
// 标记任务状态:已暂停
this.state = DownloadState.PAUSE
// 发送通知
this.publishProgressNotification()
}
open() {
promptAction.showToast({
message: '功能未实现'
})
}
async publishProgressNotification() {
let isSupportTpl: boolean;
await Notification.isSupportTemplate('downloadTemplate').then((data) => {
isSupportTpl = data;
}).catch((err) => {
Prompt.showToast({
message: `判断是否支持进度条模板时报错,error[${err}]`,
duration: 2000
})
})
if (isSupportTpl) {
// 构造模板
let template = {
name: 'downloadTemplate',
data: {
progressValue: this.progressValue, // 当前进度值
progressMaxValue: this.progressMaxValue // 最大进度值
}
};
let notificationRequest: Notification.NotificationRequest = {
id: this.notificationId,
content: {
contentType: Notification.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT,
normal: {
title: this.filename + ': ' + this.state,
text: '',
additionalText: this.progressValue + '%'
}
},
template: template
};
// 发布通知
Notification.publish(notificationRequest).then(() => {
Prompt.showToast({
message: `发布通知成功!`,
duration: 2000
})
}).catch((err) => {
Prompt.showToast({
message: `发布通知失败,error[${err}]`,
duration: 2000
})
})
} else {
Prompt.showToast({
message: '不支持downloadTemplate进度条通知模板',
duration: 2000
})
}
}
publishDownloadNotification() {
// 1.判断当前系统是否支持进度条模板
if (!this.isSupport) {
// 当前系统不支持进度条模板
console.log("not support")
return
}
// 2.准备进度条模板的参数
let template = {
name: 'downloadTemplate',
data: {
progressValue: this.progressValue,
progressMaxValue: this.progressMaxValue
}
}
let request: Notification.NotificationRequest = {
id: this.notificationId,
template: template,
wantAgent: this.wantAgentInstance,
content: {
contentType: Notification.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT,
normal: {
title: this.filename + ': ' + this.state,
text: '',
additionalText: this.progressValue + '%'
}
}
}
// 3.发送通知
Notification.publish(request)
.then(() => console.log('test', '通知发送成功'))
.catch(reason => console.log('test', '通知发送失败!', JSON.stringify(reason)))
}
}
@Extend(Button) function downloadButton() {
.width(75).height(28).fontSize(14)
}
通知意图
具体参数看官方文档
https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V2/js-apis-app-ability-wantagent-0000001493424324-V2
async aboutToAppear() {
// 1.判断当前系统是否支持进度条模板
this.isSupport = await Notification.isSupportTemplate('downloadTemplate')
// 2.创建拉取当前应用的行为意图
// 2.1.创建wantInfo信息
let wantInfo: wantAgent.WantAgentInfo = {
wants: [
{
bundleName: 'com.example.learn_2',
abilityName: 'EntryAbility',
}
],
requestCode: 0,
operationType: wantAgent.OperationType.START_ABILITY,
wantAgentFlags: [wantAgent.WantAgentFlags.CONSTANT_FLAG]
}
// 2.2.创建wantAgent实例
this.wantAgentInstance = await wantAgent.getWantAgent(wantInfo)
}
async publishProgressNotification() {
let isSupportTpl: boolean;
await Notification.isSupportTemplate('downloadTemplate').then((data) => {
isSupportTpl = data;
}).catch((err) => {
Prompt.showToast({
message: `判断是否支持进度条模板时报错,error[${err}]`,
duration: 2000
})
})
if (isSupportTpl) {
// 构造模板
let template = {
name: 'downloadTemplate',
data: {
progressValue: this.progressValue, // 当前进度值
progressMaxValue: this.progressMaxValue // 最大进度值
}
};
let notificationRequest: Notification.NotificationRequest = {
id: this.notificationId,
wantAgent: this.wantAgentInstance,
content: {
contentType: Notification.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT,
normal: {
title: this.filename + ': ' + this.state,
text: '',
additionalText: this.progressValue + '%'
}
},
template: template
};
// 发布通知
Notification.publish(notificationRequest).then(() => {
Prompt.showToast({
message: `发布通知成功!`,
duration: 2000
})
}).catch((err) => {
Prompt.showToast({
message: `发布通知失败,error[${err}]`,
duration: 2000
})
})
} else {
Prompt.showToast({
message: '不支持downloadTemplate进度条通知模板',
duration: 2000
})
}
}