import notificationManager from '@ohos.notificationManager';
import common from '@ohos.app.ability.common';
import wantAgent from '@ohos.app.ability.wantAgent';
import { WantAgent } from '@ohos.wantAgent';
import { image } from '@kit.ImageKit';
import { ImageUtil } from './ImageUtil';
import { AppUtil } from './AppUtil';
import { systemDateTime } from '@kit.BasicServicesKit';
/*** 默认通知配置类*/
export class NotificationConfig {notificationSlotType: notificationManager.SlotType = notificationManager.SlotType.SERVICE_INFORMATION;deliveryTime?: number;tapDismissed: boolean = false;autoDeletedTime?: number;wantAgent?: WantAgent;extraInfo?: Record<string, Object>;isAlertOnce: boolean = false;isStopwatch: boolean = false;isCountDown: boolean = false;isFloatingIcon: boolean = true;label?: string;badgeIconStyle?: number;showDeliveryTime: boolean = false;actionButtons?: Array<notificationManager.NotificationActionButton>;smallIcon?: image.PixelMap;largeIcon?: image.PixelMap;groupName?: string;template?: notificationManager.NotificationTemplate;distributedOption?: notificationManager.DistributedOptions;removalWantAgent?: WantAgent;badgeNumber: number = 1;appMessageId?: string;sound?: string;additionalText?: string;lockscreenPicture?: image.PixelMap;
}
/*** 通知选项接口*/
export interface NotificationOptions {id?: number;notificationSlotType?: notificationManager.SlotType;showDeliveryTime?: boolean;deliveryTime?: number;tapDismissed?: boolean;autoDeletedTime?: number;wantAgent?: WantAgent;extraInfo?: Record<string, Object>;isAlertOnce?: boolean;isStopwatch?: boolean;isCountDown?: boolean;isFloatingIcon?: boolean;label?: string;actionButtons?: Array<notificationManager.NotificationActionButton>;smallIcon?: image.PixelMap;largeIcon?: image.PixelMap;groupName?: string;template?: notificationManager.NotificationTemplate;distributedOption?: notificationManager.DistributedOptions;removalWantAgent?: WantAgent;badgeNumber?: number;appMessageId?: string;sound?: string;
}
/*** 普通文本通知接口*/
export interface NotificationBasicOptions extends NotificationOptions {title: string;text: string;additionalText?: string;lockscreenPicture?: image.PixelMap;
}
/*** 长文本通知接口*/
export interface NotificationLongTextOptions extends NotificationBasicOptions {briefText: string;longText: string;expandedTitle: string;
}
/*** 多行文本通知接口*/
export interface NotificationMultiLineOptions extends NotificationBasicOptions {briefText: string;longTitle: string;lines: Array<string>;
}
/*** 图片通知接口*/
export interface NotificationPictureOptions extends NotificationBasicOptions {briefText: string;expandedTitle: string;picture: image.PixelMap;
}
/*** 模板通知接口*/
export interface NotificationTemplateOptions extends NotificationBasicOptions {fileName: string;progressValue: number;
}/*** TODO 通知工具类* author: CSDN-鸿蒙布道师* since: 2025/04/23*/
export class NotificationUtil {private static defaultConfig: NotificationConfig = new NotificationConfig();/*** 设置默认通知配置* @param configSetter 配置设置函数*/static setDefaultConfig(configSetter: (config: NotificationConfig) => void): void {configSetter(NotificationUtil.defaultConfig);}/*** 查询通知是否已授权(异步)* @returns 是否已授权*/static async isNotificationEnabled(): Promise<boolean> {return notificationManager.isNotificationEnabled();}/*** 查询通知是否已授权(同步)* @returns 是否已授权*/static isNotificationEnabledSync(): boolean {return notificationManager.isNotificationEnabledSync();}/*** 请求通知授权* @param callBack 授权回调* @returns 是否成功授权*/static async authorizeNotification(callBack?: (grant: boolean) => void): Promise<boolean> {const isEnabled = await NotificationUtil.isNotificationEnabled();if (!isEnabled) {try {await notificationManager.requestEnableNotification(AppUtil.getContext());callBack?.(true);return true;} catch {callBack?.(false);return false;}}callBack?.(true);return true;}/*** 查询模板是否支持* @param templateName 模板名称,默认为'downloadTemplate'* @returns 是否支持*/static async isSupportTemplate(templateName: string = 'downloadTemplate'): Promise<boolean> {return notificationManager.isSupportTemplate(templateName);}/*** 查询设备是否支持分布式通知* @returns 是否支持*/static async isDistributedEnabled(): Promise<boolean> {return notificationManager.isDistributedEnabled();}/*** 发布普通文本通知* @param options 通知实体* @returns 返回通知ID*/static async publishBasic(options: NotificationBasicOptions): Promise<number> {const notificationId = options.id ?? NotificationUtil.generateNotificationId(); // 生成通知IDconst basicContent: notificationManager.NotificationBasicContent = {title: options.title,text: options.text,additionalText: options.additionalText ?? NotificationUtil.defaultConfig.additionalText,lockscreenPicture: options.lockscreenPicture ?? NotificationUtil.defaultConfig.lockscreenPicture,};const notificationContent: notificationManager.NotificationContent = {notificationContentType: notificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT,normal: basicContent,};// 构建并发布通知请求const notificationRequest = NotificationUtil.getNotificationRequest(notificationId, options, notificationContent);await notificationManager.publish(notificationRequest);return notificationId;}/*** 生成通知ID(使用时间戳作为ID)* @returns 唯一的通知ID*/static generateNotificationId(): number {return systemDateTime.getTime(true);}/*** 构建 NotificationRequest 对象* @param notificationId 通知ID* @param options 描述通知的请求参数* @param content 通知内容* @param template 模板* @returns NotificationRequest 对象*/private static getNotificationRequest(notificationId: number,options: NotificationOptions,content: notificationManager.NotificationContent,template?: notificationManager.NotificationTemplate): notificationManager.NotificationRequest {const request: notificationManager.NotificationRequest = { id: notificationId, content };// 手动为每个字段赋值request.notificationSlotType = options.notificationSlotType ?? NotificationUtil.defaultConfig.notificationSlotType;request.deliveryTime = options.deliveryTime ?? NotificationUtil.defaultConfig.deliveryTime;request.showDeliveryTime = options.showDeliveryTime ?? NotificationUtil.defaultConfig.showDeliveryTime;request.tapDismissed = options.tapDismissed ?? NotificationUtil.defaultConfig.tapDismissed;request.autoDeletedTime = options.autoDeletedTime ?? NotificationUtil.defaultConfig.autoDeletedTime;request.isAlertOnce = options.isAlertOnce ?? NotificationUtil.defaultConfig.isAlertOnce;request.isStopwatch = options.isStopwatch ?? NotificationUtil.defaultConfig.isStopwatch;request.isCountDown = options.isCountDown ?? NotificationUtil.defaultConfig.isCountDown;request.isFloatingIcon = options.isFloatingIcon ?? NotificationUtil.defaultConfig.isFloatingIcon;request.label = options.label ?? NotificationUtil.defaultConfig.label;request.actionButtons = options.actionButtons ?? NotificationUtil.defaultConfig.actionButtons;request.smallIcon = options.smallIcon ?? NotificationUtil.defaultConfig.smallIcon;request.largeIcon = options.largeIcon ?? NotificationUtil.defaultConfig.largeIcon;request.groupName = options.groupName ?? NotificationUtil.defaultConfig.groupName;request.template = template ?? NotificationUtil.defaultConfig.template;request.distributedOption = options.distributedOption ?? NotificationUtil.defaultConfig.distributedOption;request.appMessageId = options.appMessageId ?? NotificationUtil.defaultConfig.appMessageId;request.sound = options.sound ?? NotificationUtil.defaultConfig.sound;request.badgeNumber = options.badgeNumber ?? NotificationUtil.defaultConfig.badgeNumber;request.extraInfo = options.extraInfo ?? NotificationUtil.defaultConfig.extraInfo;request.wantAgent = options.wantAgent ?? NotificationUtil.defaultConfig.wantAgent;request.removalWantAgent = options.removalWantAgent ?? NotificationUtil.defaultConfig.removalWantAgent;return request;}/*** 发布长文本通知* @param options 通知实体* @returns*/static async publishLongText(options: NotificationLongTextOptions): Promise<number> {const notificationId: number = options.id ?? NotificationUtil.generateNotificationId(); //通知ID。const longTextContent: notificationManager.NotificationLongTextContent = {title: options.title,text: options.text,briefText: options.briefText,longText: options.longText,expandedTitle: options.expandedTitle}if (options.additionalText || NotificationUtil.defaultConfig.additionalText) {longTextContent.additionalText = options.additionalText ?? NotificationUtil.defaultConfig.additionalText;}if (options.lockscreenPicture || NotificationUtil.defaultConfig.lockscreenPicture) {longTextContent.lockscreenPicture = options.lockscreenPicture ?? NotificationUtil.defaultConfig.lockscreenPicture;}let notificationContent: notificationManager.NotificationContent = {notificationContentType: notificationManager.ContentType.NOTIFICATION_CONTENT_LONG_TEXT,longText: longTextContent}//通知Request对象const notificationRequest = NotificationUtil.getNotificationRequest(notificationId, options, notificationContent);await notificationManager.publish(notificationRequest); //发送通知return notificationId;}/*** 发布多文本通知* @param options 通知实体* @returns*/static async publishMultiLine(options: NotificationMultiLineOptions): Promise<number> {const notificationId: number = options.id ?? NotificationUtil.generateNotificationId(); //通知ID。const multiLineContent: notificationManager.NotificationMultiLineContent = {title: options.title,text: options.text,briefText: options.briefText,longTitle: options.longTitle,lines: options.lines}if (options.additionalText || NotificationUtil.defaultConfig.additionalText) {multiLineContent.additionalText = options.additionalText ?? NotificationUtil.defaultConfig.additionalText;}if (options.lockscreenPicture || NotificationUtil.defaultConfig.lockscreenPicture) {multiLineContent.lockscreenPicture = options.lockscreenPicture ?? NotificationUtil.defaultConfig.lockscreenPicture;}let notificationContent: notificationManager.NotificationContent = {notificationContentType: notificationManager.ContentType.NOTIFICATION_CONTENT_MULTILINE,multiLine: multiLineContent}//通知Request对象const notificationRequest = NotificationUtil.getNotificationRequest(notificationId, options, notificationContent);await notificationManager.publish(notificationRequest); //发送通知return notificationId;}/*** 发布带有图片的通知* @param options 通知实体* @returns*/static async publishPicture(options: NotificationPictureOptions): Promise<number> {const notificationId: number = options.id ?? NotificationUtil.generateNotificationId(); //通知ID。const pictureContent: notificationManager.NotificationPictureContent = {title: options.title,text: options.text,briefText: options.briefText,expandedTitle: options.expandedTitle,picture: options.picture}if (options.additionalText || NotificationUtil.defaultConfig.additionalText) {pictureContent.additionalText = options.additionalText ?? NotificationUtil.defaultConfig.additionalText;}if (options.lockscreenPicture || NotificationUtil.defaultConfig.lockscreenPicture) {pictureContent.lockscreenPicture = options.lockscreenPicture ?? NotificationUtil.defaultConfig.lockscreenPicture;}let notificationContent: notificationManager.NotificationContent = {notificationContentType: notificationManager.ContentType.NOTIFICATION_CONTENT_PICTURE,picture: pictureContent}//通知Request对象const notificationRequest = NotificationUtil.getNotificationRequest(notificationId, options, notificationContent);await notificationManager.publish(notificationRequest); //发送通知return notificationId;}/*** 发布模板的通知* @param options*/static async publishTemplate(options: NotificationTemplateOptions): Promise<number> {const notificationId: number = options.id ?? NotificationUtil.generateNotificationId(); //通知ID。const basicContent: notificationManager.NotificationBasicContent = {title: options.title,text: options.text}if (options.additionalText || NotificationUtil.defaultConfig.additionalText) {basicContent.additionalText = options.additionalText ?? NotificationUtil.defaultConfig.additionalText;}if (options.lockscreenPicture || NotificationUtil.defaultConfig.lockscreenPicture) {basicContent.lockscreenPicture = options.lockscreenPicture ?? NotificationUtil.defaultConfig.lockscreenPicture;}let notificationContent: notificationManager.NotificationContent = {notificationContentType: notificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT,normal: basicContent}//模板对象let template: notificationManager.NotificationTemplate = {name: 'downloadTemplate',data: { title: options.title, fileName: options.fileName, progressValue: options.progressValue }}//通知Request对象const notificationRequest = NotificationUtil.getNotificationRequest(notificationId, options, notificationContent, template);await notificationManager.publish(notificationRequest); //发送通知return notificationId;}/*** 取消通知,通过通知ID和通知标签取消已发布的通知,若label为空表示取消与指定通知ID相匹配的已发布通知。* @param id 通知id* @param label 通知标签,默认为空。* @returns*/static async cancel(id: number, label?: string): Promise<void> {return notificationManager.cancel(id, label);}/*** 取消本应用指定组下的通知* @param groupName 通知组名称,此名称需要在发布通知时通过NotificationRequest对象指定。* @returns*/static async cancelGroup(groupName: string): Promise<void> {return notificationManager.cancelGroup(groupName);}/*** 取消所有通知,取消当前应用所有已发布的通知。* @returns*/static async cancelAll(): Promise<void> {return notificationManager.cancelAll()}/*** 设置桌面角标个数,在应用的桌面图标上呈现。*/static async setBadge(badgeNumber: number): Promise<void> {return notificationManager.setBadgeNumber(badgeNumber);}/*** 清空桌面角标,在应用的桌面图标上呈现。*/static async clearBadge(): Promise<void> {return notificationManager.setBadgeNumber(0);}/*** 获取当前应用未删除的通知数量。*/static async getActiveNotificationCount(): Promise<number> {return notificationManager.getActiveNotificationCount();}/*** 设置桌面角标数量,来自于通知数量。*/static async setBadgeFromNotificationCount(): Promise<void> {let count = await NotificationUtil.getActiveNotificationCount();return notificationManager.setBadgeNumber(count); //设置角标}/*** 获取当前应用未删除的通知列表。*/static async getActiveNotifications(): Promise<Array<notificationManager.NotificationRequest>> {return notificationManager.getActiveNotifications();}/*** 创建指定类型的通知渠道。* @param type 要创建的通知渠道的类型*/static async addSlot(type: notificationManager.SlotType) {return notificationManager.addSlot(type);}/*** 获取一个指定类型的通知渠道。* @param type 要创建的通知渠道的类型*/static async getSlot(type: notificationManager.SlotType): Promise<notificationManager.NotificationSlot> {return notificationManager.getSlot(type);}/*** 获取此应用程序的所有通知渠道* @returns*/static async getSlots(): Promise<Array<notificationManager.NotificationSlot>> {return notificationManager.getSlots();}/*** 删除此应用程序指定类型的通知渠道* @param type 通知渠道类型,例如社交通信、服务提醒、内容咨询等类型。* @returns*/static async removeSlot(type: notificationManager.SlotType) {return notificationManager.removeSlot(type);}/*** 删除此应用程序所有通知渠道* @returns*/static async removeAllSlots() {return notificationManager.removeAllSlots();}/*** 获取压缩通知的图片(图像像素的总字节数不能超过2MB)* @param pixelMap:原始待压缩图片的PixelMap对象* @returns 返回压缩后的图片数据*/static async getCompressedPicture(src: Resource | image.PixelMap): Promise<PixelMap> {if (typeof (src as Resource).bundleName == 'string') {src = await ImageUtil.getPixelMapFromMedia((src as Resource));}let pixelMap = src as image.PixelMap;let pictureMaxSize = 2 * 1024 * 1024; //通知的图片内容(图像像素的总字节数不能超过2MB)。let pixelBytes = pixelMap.getPixelBytesNumber(); //图像像素的总字节数while (pixelBytes > pictureMaxSize) {await pixelMap.scale(0.7, 0.7, image.AntiAliasingLevel.LOW); //缩放pixelBytes = pixelMap.getPixelBytesNumber(); //图像像素的总字节数}return pixelMap;}/*** 获取压缩通知图标(图标像素的总字节数不超过192KB)* @param pixelMap:原始待压缩图片的PixelMap对象* @returns*/static async getCompressedIcon(src: Resource | image.PixelMap): Promise<PixelMap> {if (typeof (src as Resource).bundleName == 'string') {src = await ImageUtil.getPixelMapFromMedia((src as Resource));}let pixelMap = src as image.PixelMap;let pictureMaxSize = 192 * 1024; //通知图标(图标像素的总字节数不超过192KB)。let pixelBytes = pixelMap.getPixelBytesNumber(); //图像像素的总字节数while (pixelBytes > pictureMaxSize) {await pixelMap.scale(0.7, 0.7, image.AntiAliasingLevel.LOW); //缩放pixelBytes = pixelMap.getPixelBytesNumber(); //图像像素的总字节数}return pixelMap;}/*** 创建一个可拉起Ability的Want* @returns*/static async getDefaultWantAgent(): Promise<WantAgent> {const context = getContext() as common.UIAbilityContext; //获取当前上下文对象const wantAgentInfo: wantAgent.WantAgentInfo = {wants: [{deviceId: '',bundleName: context.abilityInfo.bundleName,moduleName: context.abilityInfo.moduleName,abilityName: context.abilityInfo.name,action: 'action_notice',entities: [],uri: '',}],actionType: wantAgent.OperationType.START_ABILITY | wantAgent.OperationType.SEND_COMMON_EVENT,requestCode: 0,actionFlags: [wantAgent.WantAgentFlags.CONSTANT_FLAG]};return wantAgent.getWantAgent(wantAgentInfo);}/*** 获取错误消息* @param code 错误码* @param defaultMsg 默认错误消息* @returns 对应的错误消息*/public static getErrorMsg(code: number, defaultMsg: string): string {// 定义错误码与错误消息的映射表const errorMessages = new Map<number, string>([[201, '权限校验失败!'],[202, '系统API权限校验失败!'],[401, '参数检查失败!'],[801, '该设备不支持此API!'],[1600001, '应用通知,内部错误!'],[1600002, '序列化或反序列化错误!'],[1600003, '应用连接通知服务失败!'],[1600004, '请开启应用通知开关!'],[1600005, '通知渠道关闭!'],[1600006, '通知删除失败!'],[1600007, '通知不存在!'],[1600008, '用户不存在!'],[1600009, '通知发布频度超过限制!'],[1600010, '分布式操作失败!'],[1600011, '读模板配置文件错误!'],[1600012, '内存空间不够!'],[17700001, '包名不存在!'],]);// 返回对应的错误消息,如果未找到则返回默认消息return errorMessages.get(code) ?? defaultMsg;}
}
代码如下:
import notificationManager from '@ohos.notificationManager';
import common from '@ohos.app.ability.common';
import wantAgent from '@ohos.app.ability.wantAgent';
import { WantAgent } from '@ohos.wantAgent';
import { image } from '@kit.ImageKit';
import { ImageUtil } from './ImageUtil';
import { AppUtil } from './AppUtil';
import { systemDateTime } from '@kit.BasicServicesKit';
/*** 默认通知配置类*/
export class NotificationConfig {notificationSlotType: notificationManager.SlotType = notificationManager.SlotType.SERVICE_INFORMATION;deliveryTime?: number;tapDismissed: boolean = false;autoDeletedTime?: number;wantAgent?: WantAgent;extraInfo?: Record<string, Object>;isAlertOnce: boolean = false;isStopwatch: boolean = false;isCountDown: boolean = false;isFloatingIcon: boolean = true;label?: string;badgeIconStyle?: number;showDeliveryTime: boolean = false;actionButtons?: Array<notificationManager.NotificationActionButton>;smallIcon?: image.PixelMap;largeIcon?: image.PixelMap;groupName?: string;template?: notificationManager.NotificationTemplate;distributedOption?: notificationManager.DistributedOptions;removalWantAgent?: WantAgent;badgeNumber: number = 1;appMessageId?: string;sound?: string;additionalText?: string;lockscreenPicture?: image.PixelMap;
}
/*** 通知选项接口*/
export interface NotificationOptions {id?: number;notificationSlotType?: notificationManager.SlotType;showDeliveryTime?: boolean;deliveryTime?: number;tapDismissed?: boolean;autoDeletedTime?: number;wantAgent?: WantAgent;extraInfo?: Record<string, Object>;isAlertOnce?: boolean;isStopwatch?: boolean;isCountDown?: boolean;isFloatingIcon?: boolean;label?: string;actionButtons?: Array<notificationManager.NotificationActionButton>;smallIcon?: image.PixelMap;largeIcon?: image.PixelMap;groupName?: string;template?: notificationManager.NotificationTemplate;distributedOption?: notificationManager.DistributedOptions;removalWantAgent?: WantAgent;badgeNumber?: number;appMessageId?: string;sound?: string;
}
/*** 普通文本通知接口*/
export interface NotificationBasicOptions extends NotificationOptions {title: string;text: string;additionalText?: string;lockscreenPicture?: image.PixelMap;
}
/*** 长文本通知接口*/
export interface NotificationLongTextOptions extends NotificationBasicOptions {briefText: string;longText: string;expandedTitle: string;
}
/*** 多行文本通知接口*/
export interface NotificationMultiLineOptions extends NotificationBasicOptions {briefText: string;longTitle: string;lines: Array<string>;
}
/*** 图片通知接口*/
export interface NotificationPictureOptions extends NotificationBasicOptions {briefText: string;expandedTitle: string;picture: image.PixelMap;
}
/*** 模板通知接口*/
export interface NotificationTemplateOptions extends NotificationBasicOptions {fileName: string;progressValue: number;
}/*** TODO 通知工具类* author: CSDN-鸿蒙布道师* since: 2025/04/23*/
export class NotificationUtil {private static defaultConfig: NotificationConfig = new NotificationConfig();/*** 设置默认通知配置* @param configSetter 配置设置函数*/static setDefaultConfig(configSetter: (config: NotificationConfig) => void): void {configSetter(NotificationUtil.defaultConfig);}/*** 查询通知是否已授权(异步)* @returns 是否已授权*/static async isNotificationEnabled(): Promise<boolean> {return notificationManager.isNotificationEnabled();}/*** 查询通知是否已授权(同步)* @returns 是否已授权*/static isNotificationEnabledSync(): boolean {return notificationManager.isNotificationEnabledSync();}/*** 请求通知授权* @param callBack 授权回调* @returns 是否成功授权*/static async authorizeNotification(callBack?: (grant: boolean) => void): Promise<boolean> {const isEnabled = await NotificationUtil.isNotificationEnabled();if (!isEnabled) {try {await notificationManager.requestEnableNotification(AppUtil.getContext());callBack?.(true);return true;} catch {callBack?.(false);return false;}}callBack?.(true);return true;}/*** 查询模板是否支持* @param templateName 模板名称,默认为'downloadTemplate'* @returns 是否支持*/static async isSupportTemplate(templateName: string = 'downloadTemplate'): Promise<boolean> {return notificationManager.isSupportTemplate(templateName);}/*** 查询设备是否支持分布式通知* @returns 是否支持*/static async isDistributedEnabled(): Promise<boolean> {return notificationManager.isDistributedEnabled();}/*** 发布普通文本通知* @param options 通知实体* @returns 返回通知ID*/static async publishBasic(options: NotificationBasicOptions): Promise<number> {const notificationId = options.id ?? NotificationUtil.generateNotificationId(); // 生成通知IDconst basicContent: notificationManager.NotificationBasicContent = {title: options.title,text: options.text,additionalText: options.additionalText ?? NotificationUtil.defaultConfig.additionalText,lockscreenPicture: options.lockscreenPicture ?? NotificationUtil.defaultConfig.lockscreenPicture,};const notificationContent: notificationManager.NotificationContent = {notificationContentType: notificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT,normal: basicContent,};// 构建并发布通知请求const notificationRequest = NotificationUtil.getNotificationRequest(notificationId, options, notificationContent);await notificationManager.publish(notificationRequest);return notificationId;}/*** 生成通知ID(使用时间戳作为ID)* @returns 唯一的通知ID*/static generateNotificationId(): number {return systemDateTime.getTime(true);}/*** 构建 NotificationRequest 对象* @param notificationId 通知ID* @param options 描述通知的请求参数* @param content 通知内容* @param template 模板* @returns NotificationRequest 对象*/private static getNotificationRequest(notificationId: number,options: NotificationOptions,content: notificationManager.NotificationContent,template?: notificationManager.NotificationTemplate): notificationManager.NotificationRequest {const request: notificationManager.NotificationRequest = { id: notificationId, content };// 手动为每个字段赋值request.notificationSlotType = options.notificationSlotType ?? NotificationUtil.defaultConfig.notificationSlotType;request.deliveryTime = options.deliveryTime ?? NotificationUtil.defaultConfig.deliveryTime;request.showDeliveryTime = options.showDeliveryTime ?? NotificationUtil.defaultConfig.showDeliveryTime;request.tapDismissed = options.tapDismissed ?? NotificationUtil.defaultConfig.tapDismissed;request.autoDeletedTime = options.autoDeletedTime ?? NotificationUtil.defaultConfig.autoDeletedTime;request.isAlertOnce = options.isAlertOnce ?? NotificationUtil.defaultConfig.isAlertOnce;request.isStopwatch = options.isStopwatch ?? NotificationUtil.defaultConfig.isStopwatch;request.isCountDown = options.isCountDown ?? NotificationUtil.defaultConfig.isCountDown;request.isFloatingIcon = options.isFloatingIcon ?? NotificationUtil.defaultConfig.isFloatingIcon;request.label = options.label ?? NotificationUtil.defaultConfig.label;request.actionButtons = options.actionButtons ?? NotificationUtil.defaultConfig.actionButtons;request.smallIcon = options.smallIcon ?? NotificationUtil.defaultConfig.smallIcon;request.largeIcon = options.largeIcon ?? NotificationUtil.defaultConfig.largeIcon;request.groupName = options.groupName ?? NotificationUtil.defaultConfig.groupName;request.template = template ?? NotificationUtil.defaultConfig.template;request.distributedOption = options.distributedOption ?? NotificationUtil.defaultConfig.distributedOption;request.appMessageId = options.appMessageId ?? NotificationUtil.defaultConfig.appMessageId;request.sound = options.sound ?? NotificationUtil.defaultConfig.sound;request.badgeNumber = options.badgeNumber ?? NotificationUtil.defaultConfig.badgeNumber;request.extraInfo = options.extraInfo ?? NotificationUtil.defaultConfig.extraInfo;request.wantAgent = options.wantAgent ?? NotificationUtil.defaultConfig.wantAgent;request.removalWantAgent = options.removalWantAgent ?? NotificationUtil.defaultConfig.removalWantAgent;return request;}/*** 发布长文本通知* @param options 通知实体* @returns*/static async publishLongText(options: NotificationLongTextOptions): Promise<number> {const notificationId: number = options.id ?? NotificationUtil.generateNotificationId(); //通知ID。const longTextContent: notificationManager.NotificationLongTextContent = {title: options.title,text: options.text,briefText: options.briefText,longText: options.longText,expandedTitle: options.expandedTitle}if (options.additionalText || NotificationUtil.defaultConfig.additionalText) {longTextContent.additionalText = options.additionalText ?? NotificationUtil.defaultConfig.additionalText;}if (options.lockscreenPicture || NotificationUtil.defaultConfig.lockscreenPicture) {longTextContent.lockscreenPicture = options.lockscreenPicture ?? NotificationUtil.defaultConfig.lockscreenPicture;}let notificationContent: notificationManager.NotificationContent = {notificationContentType: notificationManager.ContentType.NOTIFICATION_CONTENT_LONG_TEXT,longText: longTextContent}//通知Request对象const notificationRequest = NotificationUtil.getNotificationRequest(notificationId, options, notificationContent);await notificationManager.publish(notificationRequest); //发送通知return notificationId;}/*** 发布多文本通知* @param options 通知实体* @returns*/static async publishMultiLine(options: NotificationMultiLineOptions): Promise<number> {const notificationId: number = options.id ?? NotificationUtil.generateNotificationId(); //通知ID。const multiLineContent: notificationManager.NotificationMultiLineContent = {title: options.title,text: options.text,briefText: options.briefText,longTitle: options.longTitle,lines: options.lines}if (options.additionalText || NotificationUtil.defaultConfig.additionalText) {multiLineContent.additionalText = options.additionalText ?? NotificationUtil.defaultConfig.additionalText;}if (options.lockscreenPicture || NotificationUtil.defaultConfig.lockscreenPicture) {multiLineContent.lockscreenPicture = options.lockscreenPicture ?? NotificationUtil.defaultConfig.lockscreenPicture;}let notificationContent: notificationManager.NotificationContent = {notificationContentType: notificationManager.ContentType.NOTIFICATION_CONTENT_MULTILINE,multiLine: multiLineContent}//通知Request对象const notificationRequest = NotificationUtil.getNotificationRequest(notificationId, options, notificationContent);await notificationManager.publish(notificationRequest); //发送通知return notificationId;}/*** 发布带有图片的通知* @param options 通知实体* @returns*/static async publishPicture(options: NotificationPictureOptions): Promise<number> {const notificationId: number = options.id ?? NotificationUtil.generateNotificationId(); //通知ID。const pictureContent: notificationManager.NotificationPictureContent = {title: options.title,text: options.text,briefText: options.briefText,expandedTitle: options.expandedTitle,picture: options.picture}if (options.additionalText || NotificationUtil.defaultConfig.additionalText) {pictureContent.additionalText = options.additionalText ?? NotificationUtil.defaultConfig.additionalText;}if (options.lockscreenPicture || NotificationUtil.defaultConfig.lockscreenPicture) {pictureContent.lockscreenPicture = options.lockscreenPicture ?? NotificationUtil.defaultConfig.lockscreenPicture;}let notificationContent: notificationManager.NotificationContent = {notificationContentType: notificationManager.ContentType.NOTIFICATION_CONTENT_PICTURE,picture: pictureContent}//通知Request对象const notificationRequest = NotificationUtil.getNotificationRequest(notificationId, options, notificationContent);await notificationManager.publish(notificationRequest); //发送通知return notificationId;}/*** 发布模板的通知* @param options*/static async publishTemplate(options: NotificationTemplateOptions): Promise<number> {const notificationId: number = options.id ?? NotificationUtil.generateNotificationId(); //通知ID。const basicContent: notificationManager.NotificationBasicContent = {title: options.title,text: options.text}if (options.additionalText || NotificationUtil.defaultConfig.additionalText) {basicContent.additionalText = options.additionalText ?? NotificationUtil.defaultConfig.additionalText;}if (options.lockscreenPicture || NotificationUtil.defaultConfig.lockscreenPicture) {basicContent.lockscreenPicture = options.lockscreenPicture ?? NotificationUtil.defaultConfig.lockscreenPicture;}let notificationContent: notificationManager.NotificationContent = {notificationContentType: notificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT,normal: basicContent}//模板对象let template: notificationManager.NotificationTemplate = {name: 'downloadTemplate',data: { title: options.title, fileName: options.fileName, progressValue: options.progressValue }}//通知Request对象const notificationRequest = NotificationUtil.getNotificationRequest(notificationId, options, notificationContent, template);await notificationManager.publish(notificationRequest); //发送通知return notificationId;}/*** 取消通知,通过通知ID和通知标签取消已发布的通知,若label为空表示取消与指定通知ID相匹配的已发布通知。* @param id 通知id* @param label 通知标签,默认为空。* @returns*/static async cancel(id: number, label?: string): Promise<void> {return notificationManager.cancel(id, label);}/*** 取消本应用指定组下的通知* @param groupName 通知组名称,此名称需要在发布通知时通过NotificationRequest对象指定。* @returns*/static async cancelGroup(groupName: string): Promise<void> {return notificationManager.cancelGroup(groupName);}/*** 取消所有通知,取消当前应用所有已发布的通知。* @returns*/static async cancelAll(): Promise<void> {return notificationManager.cancelAll()}/*** 设置桌面角标个数,在应用的桌面图标上呈现。*/static async setBadge(badgeNumber: number): Promise<void> {return notificationManager.setBadgeNumber(badgeNumber);}/*** 清空桌面角标,在应用的桌面图标上呈现。*/static async clearBadge(): Promise<void> {return notificationManager.setBadgeNumber(0);}/*** 获取当前应用未删除的通知数量。*/static async getActiveNotificationCount(): Promise<number> {return notificationManager.getActiveNotificationCount();}/*** 设置桌面角标数量,来自于通知数量。*/static async setBadgeFromNotificationCount(): Promise<void> {let count = await NotificationUtil.getActiveNotificationCount();return notificationManager.setBadgeNumber(count); //设置角标}/*** 获取当前应用未删除的通知列表。*/static async getActiveNotifications(): Promise<Array<notificationManager.NotificationRequest>> {return notificationManager.getActiveNotifications();}/*** 创建指定类型的通知渠道。* @param type 要创建的通知渠道的类型*/static async addSlot(type: notificationManager.SlotType) {return notificationManager.addSlot(type);}/*** 获取一个指定类型的通知渠道。* @param type 要创建的通知渠道的类型*/static async getSlot(type: notificationManager.SlotType): Promise<notificationManager.NotificationSlot> {return notificationManager.getSlot(type);}/*** 获取此应用程序的所有通知渠道* @returns*/static async getSlots(): Promise<Array<notificationManager.NotificationSlot>> {return notificationManager.getSlots();}/*** 删除此应用程序指定类型的通知渠道* @param type 通知渠道类型,例如社交通信、服务提醒、内容咨询等类型。* @returns*/static async removeSlot(type: notificationManager.SlotType) {return notificationManager.removeSlot(type);}/*** 删除此应用程序所有通知渠道* @returns*/static async removeAllSlots() {return notificationManager.removeAllSlots();}/*** 获取压缩通知的图片(图像像素的总字节数不能超过2MB)* @param pixelMap:原始待压缩图片的PixelMap对象* @returns 返回压缩后的图片数据*/static async getCompressedPicture(src: Resource | image.PixelMap): Promise<PixelMap> {if (typeof (src as Resource).bundleName == 'string') {src = await ImageUtil.getPixelMapFromMedia((src as Resource));}let pixelMap = src as image.PixelMap;let pictureMaxSize = 2 * 1024 * 1024; //通知的图片内容(图像像素的总字节数不能超过2MB)。let pixelBytes = pixelMap.getPixelBytesNumber(); //图像像素的总字节数while (pixelBytes > pictureMaxSize) {await pixelMap.scale(0.7, 0.7, image.AntiAliasingLevel.LOW); //缩放pixelBytes = pixelMap.getPixelBytesNumber(); //图像像素的总字节数}return pixelMap;}/*** 获取压缩通知图标(图标像素的总字节数不超过192KB)* @param pixelMap:原始待压缩图片的PixelMap对象* @returns*/static async getCompressedIcon(src: Resource | image.PixelMap): Promise<PixelMap> {if (typeof (src as Resource).bundleName == 'string') {src = await ImageUtil.getPixelMapFromMedia((src as Resource));}let pixelMap = src as image.PixelMap;let pictureMaxSize = 192 * 1024; //通知图标(图标像素的总字节数不超过192KB)。let pixelBytes = pixelMap.getPixelBytesNumber(); //图像像素的总字节数while (pixelBytes > pictureMaxSize) {await pixelMap.scale(0.7, 0.7, image.AntiAliasingLevel.LOW); //缩放pixelBytes = pixelMap.getPixelBytesNumber(); //图像像素的总字节数}return pixelMap;}/*** 创建一个可拉起Ability的Want* @returns*/static async getDefaultWantAgent(): Promise<WantAgent> {const context = getContext() as common.UIAbilityContext; //获取当前上下文对象const wantAgentInfo: wantAgent.WantAgentInfo = {wants: [{deviceId: '',bundleName: context.abilityInfo.bundleName,moduleName: context.abilityInfo.moduleName,abilityName: context.abilityInfo.name,action: 'action_notice',entities: [],uri: '',}],actionType: wantAgent.OperationType.START_ABILITY | wantAgent.OperationType.SEND_COMMON_EVENT,requestCode: 0,actionFlags: [wantAgent.WantAgentFlags.CONSTANT_FLAG]};return wantAgent.getWantAgent(wantAgentInfo);}/*** 获取错误消息* @param code 错误码* @param defaultMsg 默认错误消息* @returns 对应的错误消息*/public static getErrorMsg(code: number, defaultMsg: string): string {// 定义错误码与错误消息的映射表const errorMessages = new Map<number, string>([[201, '权限校验失败!'],[202, '系统API权限校验失败!'],[401, '参数检查失败!'],[801, '该设备不支持此API!'],[1600001, '应用通知,内部错误!'],[1600002, '序列化或反序列化错误!'],[1600003, '应用连接通知服务失败!'],[1600004, '请开启应用通知开关!'],[1600005, '通知渠道关闭!'],[1600006, '通知删除失败!'],[1600007, '通知不存在!'],[1600008, '用户不存在!'],[1600009, '通知发布频度超过限制!'],[1600010, '分布式操作失败!'],[1600011, '读模板配置文件错误!'],[1600012, '内存空间不够!'],[17700001, '包名不存在!'],]);// 返回对应的错误消息,如果未找到则返回默认消息return errorMessages.get(code) ?? defaultMsg;}
}