一、导入模块。
import NotificationManager from '@ohos.notificationManager';
二、构造NotificationRequest对象,并发布通知。
1.普通文本类型通知由标题、文本内容和附加信息三个字段组成,其中标题和文本内容是必填字段。
let notificationRequest = {id: 1,content: {contentType: NotificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT, // 普通文本类型通知normal: {title: 'test_title',text: 'test_text',additionalText: 'test_additionalText',}}
}NotificationManager.publish(notificationRequest, (err) => {if (err) {console.error(`[ANS] failed to publish, error[${err}]`);return;}console.info(`[ANS] publish success`);
});
运行效果如下图所示。
2.长文本类型通知继承了普通文本类型的字段,同时新增了长文本内容、内容概要和通知展开时的标题。通知默认显示与普通文本相同,展开后,标题显示为展开后标题内容,内容为长文本内容。
运行效果如下图所示。
3.多行文本类型通知继承了普通文本类型的字段,同时新增了多行文本内容、内容概要和通知展开时的标题。通知默认显示与普通文本相同,展开后,标题显示为展开后标题内容,多行文本内容多行显示。
let notificationRequest = {id: 1,content: {contentType: NotificationManager.ContentType.NOTIFICATION_CONTENT_MULTILINE, // 多行文本类型通知multiLine: {title: 'test_title',text: 'test_text',briefText: 'test_briefText',longTitle: 'test_longTitle',lines: ['line_01', 'line_02', 'line_03', 'line_04'],}}
}// 发布通知
NotificationManager.publish(notificationRequest, (err) => {if (err) {console.error(`[ANS] failed to publish, error[${err}]`);return;}console.info(`[ANS] publish success`);
});
运行效果如下图所示。
4.图片类型通知继承了普通文本类型的字段,同时新增了图片内容、内容概要和通知展开时的标题,图片内容为PixelMap型对象,其大小不能超过2M。
// 图片构造
const color = new ArrayBuffer(60000);
let bufferArr = new Uint8Array(color);
for (var i = 0; i<bufferArr.byteLength;i++) {bufferArr[i++] = 60;bufferArr[i++] = 20;bufferArr[i++] = 220;bufferArr[i] = 100;
}
let opts = { editable:true, pixelFormat:"ARGB_8888", size: {height:100, width : 150}};
await image.createPixelMap(color, opts).then(async (pixelmap) => {await pixelmap.getImageInfo().then(imageInfo => {console.log("=====size: ====" + JSON.stringify(imageInfo.size));}).catch(err => {console.error("Failed to obtain the image pixel map information." + JSON.stringify(err));return;})let notificationRequest = {id: 1,content: {contentType: notify.ContentType.NOTIFICATION_CONTENT_PICTURE,picture: {title: 'test_title',text: 'test_text',additionalText: 'test_additionalText',picture: pixelmap,briefText: 'test_briefText',expandedTitle: 'test_expandedTitle',}},}// 发送通知NotificationManager.publish(notificationRequest, (err) => {if (err) {console.error(`[ANS] failed to publish, error[${err}]`);return;}console.info(`[ANS] publish success `);});}).catch(err=>{console.error('create pixelmap failed =========='+ JSON.stringify(err));return;})
运行效果如下图所示。
本文主要参考HarmonyOS官方文档整理而成