鸿蒙学习实战之路:通知与提醒系统:即时消息与日程管理实现

通知与提醒系统:即时消息与日程管理实现

概述

在HarmonyOS应用开发中,通知与提醒系统是连接用户与应用的重要桥梁。本文将深入探讨如何在HarmonyOS Next(API 10+)中实现高效的通知管理和智能的日程提醒功能。

官方参考资料:

基础概念

什么是HarmonyOS通知系统?

HarmonyOS通知系统是一个统一的消息传递框架,允许应用向用户展示重要信息,即使用户没有主动使用该应用。

核心特点:

  • 统一的通知管理中心
  • 多设备协同通知
  • 丰富的模板支持
  • 智能的免打扰管理

通知类型分类

在HarmonyOS Next中,通知主要分为以下几类:

  • 即时通知:需要用户立即关注的消息
  • 持续通知:在后台运行的任务状态
  • 计划通知:在特定时间触发的提醒
  • 进度通知:显示任务进度的通知

环境配置

权限声明

首先需要在module.json5文件中声明必要的权限:

{
  "module": {
    "requestPermissions": [
      {
        "name": "ohos.permission.PUBLISH_AGENT_REMINDER",
        "reason": "$string:reminder_permission_reason",
        "usedScene": {
          "abilities": ["MainAbility"],
          "when": "always"
        }
      },
      {
        "name": "ohos.permission.NOTIFICATION_CONTROLLER",
        "reason": "$string:notification_permission_reason"
      }
    ]
  }
}

导入必要模块

import notificationManager from '@ohos.notificationManager';
import reminderAgent from '@ohos.reminderAgent';
import common from '@ohos.app.ability.common';

即时消息通知实现

发布基础通知

最基本的通知发布只需要几个关键参数:

// 发布简单文本通知
async function publishBasicNotification(): Promise<void> {
  try {
    const request: notificationManager.NotificationRequest = {
      content: {
        contentType: notificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT,
        normal: {
          title: '新消息提醒',
          text: '您收到一条新的即时消息',
          additionalText: '刚刚'
        }
      },
      id: 1,  // 通知ID,用于后续更新或取消
      slotType: notificationManager.SlotType.SOCIAL_COMMUNICATION  // 使用社交通信槽位
    };
    
    await notificationManager.publish(request);
    console.info('通知发布成功');
  } catch (error) {
    console.error(`发布通知失败: ${error.code}, ${error.message}`);
  }
}

通知槽位(Slot)管理

通知槽位决定了通知的显示方式和行为:

槽位类型 适用场景 默认行为
SlotType.SOCIAL_COMMUNICATION 社交消息 振动+声音
SlotType.SERVICE_INFORMATION 服务信息 静音
SlotType.CONTENT_INFORMATION 内容更新 轻微提示
SlotType.OTHER_TYPES 其他类型 系统默认
// 创建自定义通知槽位
async function createNotificationSlot(): Promise<void> {
  const slot: notificationManager.NotificationSlot = {
    type: notificationManager.SlotType.SOCIAL_COMMUNICATION,
    level: notificationManager.SlotLevel.LEVEL_HIGH,  // 高优先级
    desc: '即时消息通知槽位',
    vibration: true,
    sound: 'notification_sound.wav',
    light: true,
    bypassDnd: false  // 不绕过免打扰
  };
  
  try {
    await notificationManager.addSlot(slot);
    console.info('通知槽位创建成功');
  } catch (error) {
    console.error(`创建槽位失败: ${error.code}, ${error.message}`);
  }
}

富媒体通知实现

HarmonyOS支持丰富的多媒体通知内容:

// 发布带图片的长文本通知
async function publishRichNotification(): Promise<void> {
  const request: notificationManager.NotificationRequest = {
    content: {
      contentType: notificationManager.ContentType.NOTIFICATION_CONTENT_LONG_TEXT,
      longText: {
        title: '详细消息通知',
        text: '这是一条包含详细内容的长文本通知,用户可以展开查看更多信息...',
        additionalText: '长文本',
        briefText: '消息摘要',
        expandedTitle: '消息详情',
        longText: '这里是完整的消息内容,可以包含大量的文本信息...',
        image: $r('app.media.message_image')  // 引用资源文件中的图片
      }
    },
    id: 2,
    slotType: notificationManager.SlotType.SOCIAL_COMMUNICATION,
    deliveryTime: new Date().getTime(),  // 立即发送
    showDeliveryTime: true  // 显示发送时间
  };
  
  await notificationManager.publish(request);
}

通知操作按钮

为通知添加交互按钮:

// 添加操作按钮的通知
async function publishNotificationWithActions(): Promise<void> {
  const wantAgentInfo: notificationManager.WantAgentInfo = {
    wants: [
      {
        bundleName: 'com.example.myapp',
        abilityName: 'MessageDetailAbility',
        action: 'action.view.detail'
      }
    ],
    operationType: notificationManager.OperationType.START_ABILITY,
    requestCode: 1001
  };
  
  const request: notificationManager.NotificationRequest = {
    content: {
      contentType: notificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT,
      normal: {
        title: '交互式通知',
        text: '点击按钮执行操作',
        additionalText: '可操作'
      }
    },
    id: 3,
    actionButtons: [
      {
        title: '回复',
        wantAgent: wantAgentInfo,
        autoCancel: true  // 点击后自动取消通知
      },
      {
        title: '标记已读',
        wantAgent: wantAgentInfo,
        autoCancel: true
      }
    ]
  };
  
  await notificationManager.publish(request);
}

日程管理提醒实现

提醒代理基础

HarmonyOS的提醒代理(ReminderAgent)提供了强大的日程提醒功能:

// 创建一次性定时提醒
async function createOneTimeReminder(): Promise<number> {
  const reminder: reminderAgent.ReminderRequest = {
    reminderType: reminderAgent.ReminderType.REMINDER_TYPE_TIMER,
    triggerTimeInSeconds: Math.floor(Date.now() / 1000) + 3600,  // 1小时后触发
    title: '会议提醒',
    content: '团队周会将在1小时后开始',
    expiredContent: '会议提醒已过期',
    snoozeContent: '会议提醒已延迟',
    notificationId: 1001,
    slotType: notificationManager.SlotType.SOCIAL_COMMUNICATION,
    wantAgent: {
      pkgName: 'com.example.myapp',
      abilityName: 'MeetingDetailAbility'
    }
  };
  
  try {
    const reminderId = await reminderAgent.publishReminder(reminder);
    console.info(`提醒创建成功,ID: ${reminderId}`);
    return reminderId;
  } catch (error) {
    console.error(`创建提醒失败: ${error.code}, ${error.message}`);
    return -1;
  }
}

日历提醒实现

基于日历事件的提醒更加精确:

// 创建日历事件提醒
async function createCalendarReminder(): Promise<number> {
  const calendarReminder: reminderAgent.ReminderRequestCalendar = {
    reminderType: reminderAgent.ReminderType.REMINDER_TYPE_CALENDAR,
    dateTime: {
      year: 2024,
      month: 6,
      day: 15,
      hour: 14,
      minute: 30,
      second: 0
    },
    repeatMonths: [1, 2, 3, 4, 5, 6],  // 重复月份
    repeatDays: [1, 15],  // 每月1号和15号
    title: '月度报告提交',
    content: '请提交本月的项目进度报告',
    expiredContent: '报告提交已过期',
    snoozeContent: '报告提醒已延迟',
    notificationId: 1002,
    slotType: notificationManager.SlotType.SERVICE_INFORMATION
  };
  
  const reminderId = await reminderAgent.publishReminder(calendarReminder);
  return reminderId;
}

提醒管理操作

// 提醒管理类
class ReminderManager {
  private reminderIds: number[] = [];
  
  // 取消特定提醒
  async cancelReminder(reminderId: number): Promise<void> {
    try {
      await reminderAgent.cancelReminder(reminderId);
      const index = this.reminderIds.indexOf(reminderId);
      if (index > -1) {
        this.reminderIds.splice(index, 1);
      }
      console.info(`提醒 ${reminderId} 已取消`);
    } catch (error) {
      console.error(`取消提醒失败: ${error.code}, ${error.message}`);
    }
  }
  
  // 取消所有提醒
  async cancelAllReminders(): Promise<void> {
    try {
      await reminderAgent.cancelAllReminders();
      this.reminderIds = [];
      console.info('所有提醒已取消');
    } catch (error) {
      console.error(`取消所有提醒失败: ${error.code}, ${error.message}`);
    }
  }
  
  // 获取有效提醒
  async getValidReminders(): Promise<reminderAgent.ReminderRequest[]> {
    try {
      const reminders = await reminderAgent.getValidReminders();
      return reminders;
    } catch (error) {
      console.error(`获取提醒失败: ${error.code}, ${error.message}`);
      return [];
    }
  }
}

高级特性

通知分组管理

对于聊天类应用,消息分组显示非常重要:

// 创建分组通知
async function publishGroupedNotification(): Promise<void> {
  const groupNotification: notificationManager.NotificationRequest = {
    content: {
      contentType: notificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT,
      normal: {
        title: '聊天群组',
        text: '3条新消息',
        additionalText: '群聊'
      }
    },
    id: 100,
    groupName: 'chat_group_001',  // 分组名称
    groupOverview: '您有3条未读消息',  // 分组概览
    slotType: notificationManager.SlotType.SOCIAL_COMMUNICATION
  };
  
  // 发布分组摘要通知
  await notificationManager.publish(groupNotification);
  
  // 发布分组内的具体消息
  const messages = [
    { id: 101, text: 'Alice: 你好!' },
    { id: 102, text: 'Bob: 项目进展如何?' },
    { id: 103, text: 'Charlie: 会议记录已上传' }
  ];
  
  for (const message of messages) {
    const messageRequest: notificationManager.NotificationRequest = {
      content: {
        contentType: notificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT,
        normal: {
          title: '群组消息',
          text: message.text,
          additionalText: '刚刚'
        }
      },
      id: message.id,
      groupName: 'chat_group_001',
      slotType: notificationManager.SlotType.SOCIAL_COMMUNICATION
    };
    
    await notificationManager.publish(messageRequest);
  }
}

进度通知实现

// 发布进度通知
class ProgressNotification {
  private request: notificationManager.NotificationRequest;
  private currentProgress: number = 0;
  
  constructor() {
    this.request = {
      content: {
        contentType: notificationManager.ContentType.NOTIFICATION_CONTENT_PROGRESS,
        progress: {
          title: '文件下载',
          text: '正在下载...',
          additionalText: '0%',
          progressValue: 0,
          maxProgress: 100,
          status: '进行中'
        }
      },
      id: 200,
      slotType: notificationManager.SlotType.SERVICE_INFORMATION,
      isOngoing: true  // 持续通知,用户无法手动清除
    };
  }
  
  // 开始进度通知
  async start(): Promise<void> {
    await notificationManager.publish(this.request);
  }
  
  // 更新进度
  async updateProgress(progress: number): Promise<void> {
    this.currentProgress = progress;
    this.request.content.progress.progressValue = progress;
    this.request.content.progress.additionalText = `${progress}%`;
    
    if (progress >= 100) {
      this.request.content.progress.status = '已完成';
      this.request.isOngoing = false;  // 完成后允许用户清除
    }
    
    await notificationManager.publish(this.request);
  }
  
  // 完成进度
  async complete(): Promise<void> {
    await this.updateProgress(100);
  }
}

智能免打扰集成

// 检查和管理免打扰设置
async function manageDndSettings(): Promise<void> {
  try {
    // 获取当前免打扰模式
    const dndMode = await notificationManager.getDoNotDisturb();
    
    console.info(`当前免打扰模式: ${dndMode.type}`);
    
    // 检查是否可以发送通知
    if (dndMode.type === notificationManager.DoNotDisturbType.NONE) {
      console.info('可以正常发送通知');
    } else {
      console.info('当前处于免打扰模式,通知可能被静音');
    }
    
  } catch (error) {
    console.error(`获取免打扰设置失败: ${error.code}, ${error.message}`);
  }
}

总结与最佳实践

通过本文的学习,我们深入探讨了HarmonyOS Next中的通知与提醒系统实现,从基础概念到高级特性,全面掌握了即时消息通知和日程提醒的开发技能。

核心要点回顾

  • 通知系统基础:理解了通知的类型、权限配置和槽位管理机制
  • 即时消息实现:掌握了基础通知、富媒体通知和交互式通知的开发方法
  • 日程管理能力:学习了一次性提醒和日历事件提醒的创建与管理
  • 高级特性应用:实现了通知分组、进度通知和免打扰集成等功能

实践建议

在实际项目开发中,建议遵循以下最佳实践:

  1. 合理的通知频率:避免过于频繁的通知,影响用户体验
  2. 精准的权限管理:仅请求必要的通知权限,并提供清晰的使用说明
  3. 场景化的槽位选择:根据通知类型选择合适的槽位,提供一致的用户体验
  4. 完善的错误处理:添加适当的错误捕获和重试机制,确保通知可靠性
  5. 测试驱动开发:在不同设备和系统版本上进行充分测试,确保兼容性

未来展望

随着HarmonyOS生态的不断发展,通知与提醒系统也在持续演进。未来我们可以期待:

  • 更多元化的通知模板和交互方式
  • 更智能的用户行为分析和个性化通知推送
  • 更深入的多设备协同体验,实现通知在不同设备间的无缝流转
  • 更丰富的系统集成能力,与日历、任务管理等系统功能深度融合

继续学习

想要进一步提升HarmonyOS应用开发能力,可以关注以下相关主题:

  • HarmonyOS分布式任务调度
  • 后台任务管理与优化
  • 用户隐私保护最佳实践
  • 应用性能调优技巧

通过合理利用通知与提醒功能,我们可以构建出更加智能、高效、用户友好的HarmonyOS应用,为用户提供卓越的移动体验。

祝您开发顺利!

需要参加鸿蒙认证的请点击 鸿蒙认证链接

posted @ 2025-11-30 01:15  时间煮鱼  阅读(11)  评论(0)    收藏  举报