鸿蒙——通知

一、定义

通知是系统或应用向用户展示的即时信息提示,在不打扰用户当前操作的前提下传达重要信息

二、存在原因

  1. **后台通信:**应用退到后台时仍能与用户沟通;服务端消息能及时推送给用户

  2. **非打扰式提醒:**不中断用户当前操作;用户可自主决定何时查看

  3. **进度可视化:**让用户知道后台任务状态(如下载进度45%)

  4. **历史记录:**重要信息不会错过,可随时回看

即为在用户不被强制中断的前提下,确保重要信息能送达

三、通知业务流程

由通知子系统、通知发送端、通知订阅端组成

定义:

通知发送端:为第三方应用或系统应用

通知子系统:用于管理和分发通知的核心模块,为开发者提供高效、统一的通知管理能力(分布式能力),且为用户提供一致的通知体验(标准化接口)

通知订阅端:只能为系统应用

流程顺序:通知产生于应用(发送端),通过进程间通信(IPC)发送到通知子系统,再分发给订阅端

四、通知发布(产生)

分类:基础类型通知发布、进度条类型通知发布

用途:

基础类:主用于发送短信息、提示信息、广告等;支持类型:普通文本、长文本、多行文本

进度条类:主用于文件下载、事务处理进度显示;类型:进度条模块(模板名、数据)

步骤:

|-----------------------------|---------------|
| 基础类型通知发布 | 进度条类型通知发布 |
| 导入模块 | 导入模块 |
| 请求通知授权 | 请求通知授权 |
| 构造NotifcationRequest对象并发布通知 | 查询系统是否支持进度条模板 |
| | 构造进度条对象并发布通知 |
[通知发布步骤]

五、具体代码:

基础类型通知发布

导入模块:

bash 复制代码
import { notificationManager } from '@kit.NotificationKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { common } from '@kit.AbilityKit';

引入通知管理、错误处理和UI上下文相关的API

请求通知授权:

核心代码

bash 复制代码
  let context = getContext(this) as common.UIAbilityContext
  notificationManager.isNotificationEnabled().then((data: boolean) => {
  if(!data){ // 如果未授权
    notificationManager.requestEnableNotification(context) // 弹出授权对话框
  }
})

完整代码:

bash 复制代码
private isEnableNotify(){
    let context = getContext(this) as common.UIAbilityContext;
    notificationManager.isNotificationEnabled().then((data: boolean) => {
      if(!data){
        notificationManager.requestEnableNotification(context).then(() => {
          this.message="请求启用通知成功";
        }).catch((err : BusinessError) => {
          if(1600004 == err.code){
            this.message="拒绝请求启用通知,错误代码: " + err.code + ", 错误信息:" + err.message;
            return;
          } else {
            this.message="请求启用通知失败,错误代码: " + err.code + ", 错误信息" + err.message;
            return;
          }
        });
        this.message="正在请求启用通知,相关信息: " + JSON.stringify(data);
      }
    }).catch((err : BusinessError) => {
      this.message="不允许请求启用通知,错误代码: " + err.code + ", 错误信息:" + err.message;
    });
  }

构造NotificationRequest对象

核心代码:

bash 复制代码
 let notificationRequest: notificationManager.NotificationRequest = {
      id: 3,
      content: {
        notificationContentType: notificationManager.ContentType.NOTIFICATION_CONTENT_MULTILINE, // 多行文本类型通知
        multiLine: {
          title: '1',
          text: '2',
          briefText: '3',// 优先显示long title 以及lines 但缺少信息title text briftext 的信息会报错
          longTitle:'信息通知',
          lines:['2501','当你触及你所不能到达的高度,你会有压力的','走呗,冲呗,烂命一条就是干']
        }
      }
    };

发布通知

核心代码

bash 复制代码
notificationManager.publish(notificationRequest, (err: BusinessError) => {
  if (err) {
    // 发布失败处理
    this.message="发布基础通知错误: " + err.code;
  } else {
    // 发布成功
    this.message="发布基础通知成功";
  }
});

构造与发布在同一个方法内完整代码

bash 复制代码
    private wenben(){//发布基础
    this.message="正在发布基础通知,请稍候!";
    let notificationRequest: notificationManager.NotificationRequest = {
      id: 3,
      content: {
        notificationContentType: notificationManager.ContentType.NOTIFICATION_CONTENT_MULTILINE, // 多行文本类型通知
        multiLine: {
          title: '1',
          text: '2',
          briefText: '3',// 优先显示long title 以及lines 但缺少信息title text briftext 的信息会报错
          longTitle:'信息通知',
          lines:['2501','当你触及你所不能到达的高度,你会有压力的','走呗,冲呗,烂命一条就是干']
        }
      }
    };
    notificationManager.publish(notificationRequest, (err: BusinessError) => {
      if (err) {
        this.message="发布基础通知错误: " + err.code + ", " + err.message;
      }
      this.message="发布基础通知成功";
    });
  }

进度条类型通知发布:省略导入模块与请求通知授权

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

核心代码

bash 复制代码
notificationManager.isSupportTemplate('downloadTemplate').then((data:boolean) => {
  this.isSupportTpl = data; // 保存支持状态
  this.message="支持下载模板通知。" + JSON.stringify(data);
  if (this.isSupportTpl) {
    // 支持模板 → 继续构造通知
  } else {
    // 不支持 → 提示用户
    this.message="不支持进度条通知条发布";
  }
})

构造进度条对象

核心代码:

bash 复制代码
let notificationRequest: notificationManager.NotificationRequest = {
  id: 5,
  content: {
    notificationContentType: notificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT,
    normal: {
      title: 'kafka',
      text: '消息队列',
      additionalText: '存储爆了'
    }
  },
  // 重点:进度条模板配置
  template: {
    name: 'downloadTemplate', // 固定模板名
    data: { 
      title: 'KAFKA', // 任务标题
      fileName: 'jdk.apk', // 文件名
      progressValue: 45 // 进度值(0-100)
    }
  }
};

发布通知

bash 复制代码
 notificationManager.publish(notificationRequest, (err: BusinessError) => {
          if (err) {
            this.message="发布进度条通知错误: " + err.code + ", " + err.message;
            return;
          }
          this.message="发布进度条通知成功";
        });

三合一总方法

bash 复制代码
 private  jdt(){
      notificationManager.isSupportTemplate('downloadTemplate').then((data:boolean) => {
      this.message="支持下载模板通知。" + JSON.stringify(data);
      this.isSupportTpl = data;
      if (this.isSupportTpl) {
        let notificationRequest: notificationManager.NotificationRequest = {
          id: 5,
          content: {
            notificationContentType: notificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT,
            normal: {
              title: 'kafka',
              text: '消息队列',
              additionalText: '存储爆了'
            }
          },
          // 构造进度条模板,name字段当前需要固定配置为downloadTemplate
          template: {
            name: 'downloadTemplate',
            data: { title: 'KAFKA', fileName: 'jdk.apk', progressValue: 45 }
          }
        }
        // 发布通知
        this.message="正在发布进度条通知,请稍候!";
        notificationManager.publish(notificationRequest, (err: BusinessError) => {
          if (err) {
            this.message="发布进度条通知错误: " + err.code + ", " + err.message;
            return;
          }
          this.message="发布进度条通知成功";
        });
      }else{
        this.message="不支持进度条通知条发布";
      }
    }).catch((err: BusinessError) => {
      this.message="查询错误,错误代码:"+ err.code + ", 错误信息:" + err.message;
    });
  }

全部完整代码

bash 复制代码
import { notificationManager } from '@kit.NotificationKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { common } from '@kit.AbilityKit';

@Entry
@Component
struct Index {
  @State message: string = '';
  private isSupportTpl: boolean = false;
  //展示通知
  private isEnableNotify(){
    let context = getContext(this) as common.UIAbilityContext;
    notificationManager.isNotificationEnabled().then((data: boolean) => {
      if(!data){
        notificationManager.requestEnableNotification(context).then(() => {
          this.message="请求启用通知成功";
        }).catch((err : BusinessError) => {
          if(1600004 == err.code){
            this.message="拒绝请求启用通知,错误代码: " + err.code + ", 错误信息:" + err.message;
            return;
          } else {
            this.message="请求启用通知失败,错误代码: " + err.code + ", 错误信息" + err.message;
            return;
          }
        });
        this.message="正在请求启用通知,相关信息: " + JSON.stringify(data);
      }
    }).catch((err : BusinessError) => {
      this.message="不允许请求启用通知,错误代码: " + err.code + ", 错误信息:" + err.message;
    });
  }

  private wenben(){//发布基础
    this.message="正在发布基础通知,请稍候!";
    let notificationRequest: notificationManager.NotificationRequest = {
      id: 3,
      content: {
        notificationContentType: notificationManager.ContentType.NOTIFICATION_CONTENT_MULTILINE, // 多行文本类型通知
        multiLine: {
          title: '1',
          text: '2',
          briefText: '3',// 优先显示long title 以及lines 但缺少信息title text briftext 的信息会报错
          longTitle:'信息通知',
          lines:['2501','当你触及你所不能到达的高度,你会有压力的','走呗,冲呗,烂命一条就是干']
        }
      }
    };
    notificationManager.publish(notificationRequest, (err: BusinessError) => {
      if (err) {
        this.message="发布基础通知错误: " + err.code + ", " + err.message;
      }
      this.message="发布基础通知成功";
    });
  }
  //进度条
  private  jdt(){
      notificationManager.isSupportTemplate('downloadTemplate').then((data:boolean) => {
      this.message="支持下载模板通知。" + JSON.stringify(data);
      this.isSupportTpl = data;
      //死脑子快想这是干什么的 上面三行
      if (this.isSupportTpl) {
        let notificationRequest: notificationManager.NotificationRequest = {
          id: 5,
          content: {
            notificationContentType: notificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT,
            normal: {
              title: 'kafka',
              text: '消息队列',
              additionalText: '存储爆了'
            }
          },
          // 构造进度条模板,name字段当前需要固定配置为downloadTemplate
          template: {
            name: 'downloadTemplate',
            data: { title: 'KAFKA', fileName: 'jdk.apk', progressValue: 45 }
          }
        }
        // 发布通知
        this.message="正在发布进度条通知,请稍候!";
        notificationManager.publish(notificationRequest, (err: BusinessError) => {
          if (err) {
            this.message="发布进度条通知错误: " + err.code + ", " + err.message;
            return;
          }
          this.message="发布进度条通知成功";
        });
      }else{
        this.message="不支持进度条通知条发布";
      }
    }).catch((err: BusinessError) => {
      this.message="查询错误,错误代码:"+ err.code + ", 错误信息:" + err.message;
    });
  }
  //取消通知
  private cancelAllNotifications() {
    notificationManager.cancelAll((err: BusinessError) => {
      if (err) {
        this.message = `取消所有通知失败:错误码=${err.code},信息=${err.message}`;
      } else {
        this.message = "已成功取消所有通知";
      }
    });
  }
  build() {
    Column({ space: 10 }) {
      Text("Notifications Kit").fontSize(48)
      Button("请求通知授权").size({ width: 260, height: 50 }).backgroundColor(Color.Brown)
        .onClick(() => { this.isEnableNotify(); })
      Button("发布基础类型通知").size({ width: 260, height: 50 }).backgroundColor(Color.Gray)
        .onClick(() => { this.wenben(); })
      Button("发布进度条通知").size({ width: 260, height: 50 }).backgroundColor(Color.Blue)
        .onClick(() => { this.jdt(); })
      Button("取消通知").size({ width: 260, height: 50 }).backgroundColor('ox000000')
        .onClick(() => { this.cancelAllNotifications(); })
      Text(this.message).size({ width: 260 }).fontSize(20)
    }
    .padding(10).size({ width: "100%", height: '100%' })

  }


}
相关推荐
周胡杰5 小时前
鸿蒙preferences单多例使用,本地存储类
缓存·华为·harmonyos·preferences·鸿蒙本地存储
IvanCodes5 小时前
[鸿蒙2025领航者闯关] 共享终端的隐形守护者:基于 HarmonyOS 6 的全链路隐私闭环实战
华为·harmonyos·鸿蒙
芒鸽10 小时前
鸿蒙PC上FFmpeg+Electron的Encode Smoke(P2) 排错实录:从“无法播放/时长为 0”到“保留画面且转完整时长”
ffmpeg·electron·harmonyos
2501_9444490812 小时前
帮助中心页面 Cordova&OpenHarmony 混合开发实战
harmonyos
航Hang*12 小时前
第二章:网络系统建设与运维(中级)——华为设备基本命令
运维·计算机网络·华为·ensp·交换机
北方的流星13 小时前
华为PPPoE协议的配置
运维·网络·华为
独自归家的兔13 小时前
基于 cosyvoice-v3-plus 的 个人音色复刻 (华为OBS)
人工智能·华为·语音识别
DARLING Zero two♡13 小时前
0-Day 极速响应:基于 vLLM-Ascend 在昇腾 NPU 上部署 Qwen2.5 的实战避坑指南
华为·gpu算力·vllm
北方的流星14 小时前
华为帧中继配置
运维·网络·华为