HarmonyOS_ArkTs_API(7)

概述

通知系统是"梦想生活规划师"应用的重要组成部分,负责向用户传递应用内的重要信息、提醒和更新。该系统基于鸿蒙HarmonyOS ArkTS构建,利用本地通知和远程推送技术,确保用户及时了解与其梦想和任务相关的关键提醒。通知系统实现了多类型通知管理、智能提醒策略和个性化通知设置,增强用户体验并提高应用的参与度。

通知类型

系统支持多种通知类型,包括:

  1. 截止日期提醒 - 提醒用户任务或梦想即将到期
  2. 进度更新 - 通知用户梦想进度达到特定里程碑
  3. 社区互动 - 提醒用户收到评论、点赞等社区活动
  4. 系统公告 - 应用更新、新功能或维护信息
  5. 激励提醒 - 鼓励性消息和成就庆祝

技术实现

本地通知管理

系统使用鸿蒙API实现本地通知的创建和管理:

import notification from '@ohos.notification';
import image from '@ohos.multimedia.image';
import reminderAgent from '@ohos.reminderAgent';
import wantAgent from '@ohos.app.ability.wantAgent';

// 通知管理类
export class NotificationManager {
  private static instance: NotificationManager;
  
  private constructor() {}
  
  static getInstance(): NotificationManager {
    if (!NotificationManager.instance) {
      NotificationManager.instance = new NotificationManager();
    }
    return NotificationManager.instance;
  }
  
  // 发送基本通知
  async sendBasicNotification(id: number, title: string, content: string, onGoingFlag: boolean = false): Promise<void> {
    try {
      // 创建通知请求
      const notificationRequest: notification.NotificationRequest = {
        id: id,
        content: {
          contentType: notification.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT,
          normal: {
            title: title,
            text: content,
            additionalText: '梦想生活规划师'
          }
        },
        showDeliveryTime: true,
        deliveryTime: new Date().getTime(),
        badgeIconStyle: notification.BadgeStyle.NONE,
        autoDeletedTime: new Date().getTime() + 24 * 60 * 60 * 1000, // 24小时后自动删除
        onGoing: onGoingFlag,
        actionButtons: [
          {
            title: '查看详情',
            wantAgent: await this.createViewWantAgent()
          }
        ],
        slotType: notification.SlotType.SOCIAL_COMMUNICATION
      };
      
      // 发布通知
      await notification.publish(notificationRequest);
      console.info(`通知已发送,ID: ${id}`);
    } catch (error) {
      console.error(`发送通知失败: ${error instanceof Error ? error.message : String(error)}`);
      throw new Error(`发送通知失败: ${error instanceof Error ? error.message : String(error)}`);
    }
  }
  
  // 发送图片通知
  async sendPictureNotification(id: number, title: string, content: string, picturePath: string): Promise<void> {
    try {
      // 创建图片对象
      const imageSource = image.createImageSource(picturePath);
      const pixelMap = await imageSource.createPixelMap();
      
      // 创建通知请求
      const notificationRequest: notification.NotificationRequest = {
        id: id,
        content: {
          contentType: notification.ContentType.NOTIFICATION_CONTENT_PICTURE,
          picture: {
            title: title,
            text: content,
            expandedTitle: title,
            briefText: content,
            picture: pixelMap
          }
        },
        showDeliveryTime: true,
        deliveryTime: new Date().getTime(),
        badgeIconStyle: notification.BadgeStyle.NONE,
        slotType: notification.SlotType.CONTENT_INFORMATION
      };
      
      // 发布通知
      await notification.publish(notificationRequest);
      console.info(`图片通知已发送,ID: ${id}`);
    } catch (error) {
      console.error(`发送图片通知失败: ${error instanceof Error ? error.message : String(error)}`);
      throw new Error(`发送图片通知失败: ${error instanceof Error ? error.message : String(error)}`);
    }
  }
  
  // 创建通知点击事件的WantAgent
  private async createViewWantAgent(): Promise<wantAgent.WantAgent> {
    try {
      const wantAgentInfo: wantAgent.WantAgentInfo = {
        wants: [{
          bundleName: AppContext.getContext().applicationInfo.name,
          abilityName: 'EntryAbility',
          parameters: { 
            source: 'notification'
          }
        }],
        operationType: wantAgent.OperationType.START_ABILITY,
        requestCode: 0,
        wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG]
      };
      
      return await wantAgent.getWantAgent(wantAgentInfo);
    } catch (error) {
      console.error(`创建WantAgent失败: ${error instanceof Error ? error.message : String(error)}`);
      throw error;
    }
  }
  
  // 取消通知
  async cancelNotification(id: number): Promise<void> {
    try {
      await notification.cancel(id);
      console.info(`通知已取消,ID: ${id}`);
    } catch (error) {
      console.error(`取消通知失败: ${error instanceof Error ? error.message : String(error)}`);
      throw new Error(`取消通知失败: ${error instanceof Error ? error.message : String(error)}`);
    }
  }
  
  // 取消所有通知
  async cancelAllNotifications(): Promise<void> {
    try {
      await notification.cancelAll();
      console.info('所有通知已取消');
    } catch (error) {
      console.error(`取消所有通知失败: ${error instanceof Error ? error.message : String(error)}`);
      throw new Error(`取消所有通知失败: ${error instanceof Error ? error.message : String(error)}`);
    }
  }
  
  // 获取通知设置
  async getNotificationSlotSettings(slotType: notification.SlotType): Promise<boolean> {
    try {
      const notificationSlot = await notification.getSlot(slotType);
      return notificationSlot.enabled;
    } catch (error) {
      console.error(`获取通知设置失败: ${error instanceof Error ? error.message : String(error)}`);
      return false;
    }
  }
}

提醒代理服务

为任务和梦想创建基于时间的提醒:

export class ReminderService {
  // 创建任务截止日期提醒
  static async createTaskDeadlineReminder(task: Task): Promise<number> {
    if (!task.deadline) {
      console.info('任务没有截止日期,跳过创建提醒');
      return -1;
    }
    
    try {
      const deadlineDate = new Date(task.deadline);
      
      // 创建提醒
      const reminderRequest: reminderAgent.ReminderRequest = {
        reminderType: reminderAgent.ReminderType.REMINDER_TYPE_ALARM,
        actionButton: [
          {
            title: '查看',
            type: reminderAgent.ActionButtonType.ACTION_BUTTON_TYPE_OPEN
          },
          {
            title: '推迟',
            type: reminderAgent.ActionButtonType.ACTION_BUTTON_TYPE_SNOOZE
          }
        ],
        wantAgent: {
          pkgName: AppContext.getContext().applicationInfo.name,
          abilityName: 'EntryAbility',
          uri: `task/${task.id}`,
          parameters: {
            source: 'reminder',
            taskId: task.id
          }
        },
        maxScreenWantAgent: {
          pkgName: AppContext.getContext().applicationInfo.name,
          abilityName: 'EntryAbility',
          uri: `task/${task.id}`,
          parameters: {
            source: 'reminder',
            taskId: task.id
          }
        },
        title: '任务截止提醒',
        content: `${task.title} 即将到期`,
        expiredContent: `任务 "${task.title}" 已到期`,
        snoozeContent: '稍后再提醒',
        notificationId: task.id,
        slotType: notification.SlotType.CONTENT_INFORMATION,
        // 设置提前24小时提醒
        timeInterval: {
          start: deadlineDate.getTime() - 24 * 60 * 60 * 1000,
          end: deadlineDate.getTime()
        },
        ringDuration: 10,
        snoozeTimes: 3,
        snoozeInterval: 5 * 60, // 5分钟后再次提醒
        title: '任务提醒',
        content: `任务"${task.title}"即将到期`,
      };
      
      // 发布提醒
      const reminderId = await reminderAgent.publishReminder(reminderRequest);
      console.info(`任务提醒已创建,ID: ${reminderId}, 任务: ${task.title}`);
      
      return reminderId;
    } catch (error) {
      console.error(`创建任务提醒失败: ${error instanceof Error ? error.message : String(error)}`);
      return -1;
    }
  }
  
  // 创建梦想目标日期提醒
  static async createDreamTargetDateReminder(dream: Dream): Promise<number> {
    if (!dream.targetDate) {
      console.info('梦想没有目标日期,跳过创建提醒');
      return -1;
    }
    
    try {
      const targetDate = new Date(dream.targetDate);
      
      // 创建提醒
      const reminderRequest: reminderAgent.ReminderRequest = {
        reminderType: reminderAgent.ReminderType.REMINDER_TYPE_CALENDAR,
        actionButton: [
          {
            title: '查看',
            type: reminderAgent.ActionButtonType.ACTION_BUTTON_TYPE_OPEN
          }
        ],
        wantAgent: {
          pkgName: AppContext.getContext().applicationInfo.name,
          abilityName: 'EntryAbility',
          uri: `dream/${dream.id}`,
          parameters: {
            source: 'reminder',
            dreamId: dream.id
          }
        },
        title: '梦想目标日提醒',
        content: `"${dream.title}" 的目标日期已到`,
        notificationId: dream.id + 10000, // 避免与任务ID冲突
        slotType: notification.SlotType.SERVICE_INFORMATION,
        dateTime: {
          year: targetDate.getFullYear(),
          month: targetDate.getMonth() + 1,
          day: targetDate.getDate(),
          hour: 9,
          minute: 0
        }
      };
      
      // 发布提醒
      const reminderId = await reminderAgent.publishReminder(reminderRequest);
      console.info(`梦想提醒已创建,ID: ${reminderId}, 梦想: ${dream.title}`);
      
      return reminderId;
    } catch (error) {
      console.error(`创建梦想提醒失败: ${error instanceof Error ? error.message : String(error)}`);
      return -1;
    }
  }
  
  // 取消提醒
  static async cancelReminder(reminderId: number): Promise<void> {
    if (reminderId <= 0) {
      return;
    }
    
    try {
      await reminderAgent.cancelReminder(reminderId);
      console.info(`提醒已取消,ID: ${reminderId}`);
    } catch (error) {
      console.error(`取消提醒失败: ${error instanceof Error ? error.message : String(error)}`);
    }
  }
  
  // 获取所有提醒
  static async getAllReminders(): Promise<reminderAgent.ReminderRequest[]> {
    try {
      const reminders = await reminderAgent.getValidReminders();
      console.info(`获取到${reminders.length}个有效提醒`);
      return reminders;
    } catch (error) {
      console.error(`获取提醒列表失败: ${error instanceof Error ? error.message : String(error)}`);
      return [];
    }
  }
}

远程推送服务集成

集成鸿蒙推送服务,实现远程通知:

import push from '@ohos.push.core';
import { PreferenceManager } from '../data/PreferenceManager';

export class PushService {
  private static instance: PushService;
  private isRegistered: boolean = false;
  
  private constructor() {}
  
  static getInstance(): PushService {
    if (!PushService.instance) {
      PushService.instance = new PushService();
    }
    return PushService.instance;
  }
  
  // 初始化推送服务
  async init(): Promise<void> {
    try {
      // 注册推送服务
      await this.registerPushService();
      
      // 添加推送消息监听器
      push.on('message', (message: push.Message) => {
        this.handlePushMessage(message);
      });
      
      console.info('推送服务初始化成功');
    } catch (error) {
      console.error(`推送服务初始化失败: ${error instanceof Error ? error.message : String(error)}`);
    }
  }
  
  // 注册推送服务
  private async registerPushService(): Promise<void> {
    if (this.isRegistered) {
      return;
    }
    
    try {
      const result = await push.register();
      
      if (result && result.regId) {
        // 保存注册ID
        const prefManager = PreferenceManager.getInstance();
        await prefManager.putString('push_registration_id', result.regId);
        
        // 将注册ID发送到服务器
        await this.sendRegistrationIdToServer(result.regId);
        
        this.isRegistered = true;
        console.info(`推送服务注册成功,ID: ${result.regId}`);
      }
    } catch (error) {
      console.error(`推送服务注册失败: ${error instanceof Error ? error.message : String(error)}`);
      throw error;
    }
  }
  
  // 向服务器发送注册ID
  private async sendRegistrationIdToServer(regId: string): Promise<void> {
    try {
      const userId = await getUserId();
      
      if (!userId) {
        console.info('用户未登录,暂不发送推送注册ID');
        return;
      }
      
      const response = await request(
        RequestMethod.POST,
        '/users/push-token',
        { 
          userId: userId,
          pushToken: regId,
          platform: 'harmonyos'
        }
      );
      
      console.info('推送注册ID已发送到服务器');
    } catch (error) {
      console.error(`发送推送注册ID失败: ${error instanceof Error ? error.message : String(error)}`);
    }
  }
  
  // 处理接收到的推送消息
  private handlePushMessage(message: push.Message): void {
    try {
      console.info(`收到推送消息: ${JSON.stringify(message)}`);
      
      if (!message.data) {
        console.error('推送消息没有数据');
        return;
      }
      
      // 解析推送数据
      const data = JSON.parse(message.data);
      
      // 根据消息类型处理
      switch (data.type) {
        case 'dream_reminder':
          this.handleDreamReminder(data);
          break;
        case 'task_reminder':
          this.handleTaskReminder(data);
          break;
        case 'social_notification':
          this.handleSocialNotification(data);
          break;
        case 'system_announcement':
          this.handleSystemAnnouncement(data);
          break;
        default:
          console.info(`未知的推送消息类型: ${data.type}`);
      }
    } catch (error) {
      console.error(`处理推送消息失败: ${error instanceof Error ? error.message : String(error)}`);
    }
  }
  
  // 处理梦想提醒
  private async handleDreamReminder(data: any): Promise<void> {
    try {
      const notificationManager = NotificationManager.getInstance();
      await notificationManager.sendBasicNotification(
        data.dreamId,
        data.title || '梦想提醒',
        data.content || '您有一个梦想需要关注'
      );
    } catch (error) {
      console.error(`处理梦想提醒失败: ${error instanceof Error ? error.message : String(error)}`);
    }
  }
  
  // 处理任务提醒
  private async handleTaskReminder(data: any): Promise<void> {
    try {
      const notificationManager = NotificationManager.getInstance();
      await notificationManager.sendBasicNotification(
        data.taskId,
        data.title || '任务提醒',
        data.content || '您有一个任务需要关注'
      );
    } catch (error) {
      console.error(`处理任务提醒失败: ${error instanceof Error ? error.message : String(error)}`);
    }
  }
  
  // 处理社交通知
  private async handleSocialNotification(data: any): Promise<void> {
    try {
      const notificationManager = NotificationManager.getInstance();
      
      if (data.imageUrl) {
        // 下载图片
        const imagePath = await downloadImage(data.imageUrl);
        
        if (imagePath) {
          await notificationManager.sendPictureNotification(
            data.notificationId,
            data.title || '社区动态',
            data.content || '有用户与您的内容进行了互动',
            imagePath
          );
          return;
        }
      }
      
      // 如果没有图片或下载失败,发送普通通知
      await notificationManager.sendBasicNotification(
        data.notificationId,
        data.title || '社区动态',
        data.content || '有用户与您的内容进行了互动'
      );
    } catch (error) {
      console.error(`处理社交通知失败: ${error instanceof Error ? error.message : String(error)}`);
    }
  }
  
  // 处理系统公告
  private async handleSystemAnnouncement(data: any): Promise<void> {
    try {
      const notificationManager = NotificationManager.getInstance();
      await notificationManager.sendBasicNotification(
        data.announcementId,
        data.title || '系统公告',
        data.content || '有新的系统公告'
      );
    } catch (error) {
      console.error(`处理系统公告失败: ${error instanceof Error ? error.message : String(error)}`);
    }
  }
  
  // 注销推送服务
  async unregister(): Promise<void> {
    try {
      await push.unregister();
      this.isRegistered = false;
      console.info('推送服务已注销');
    } catch (error) {
      console.error(`注销推送服务失败: ${error instanceof Error ? error.message : String(error)}`);
    }
  }
}

通知设置页面

用户可以通过设置页面管理通知偏好:

@Entry
@Component
struct NotificationSettingsPage {
  @State allNotifications: boolean = true;
  @State taskReminders: boolean = true;
  @State dreamReminders: boolean = true;
  @State socialNotifications: boolean = true;
  @State systemAnnouncements: boolean = true;
  
  aboutToAppear() {
    this.getNotificationSettings();
  }
  
  async getNotificationSettings() {
    const prefManager = PreferenceManager.getInstance();
    this.allNotifications = await prefManager.getBoolean('notifications_enabled', true);
    this.taskReminders = await prefManager.getBoolean('task_reminders_enabled', true);
    this.dreamReminders = await prefManager.getBoolean('dream_reminders_enabled', true);
    this.socialNotifications = await prefManager.getBoolean('social_notifications_enabled', true);
    this.systemAnnouncements = await prefManager.getBoolean('system_announcements_enabled', true);
  }
  
  async saveSettings() {
    try {
      const prefManager = PreferenceManager.getInstance();
      await prefManager.putBoolean('notifications_enabled', this.allNotifications);
      await prefManager.putBoolean('task_reminders_enabled', this.taskReminders);
      await prefManager.putBoolean('dream_reminders_enabled', this.dreamReminders);
      await prefManager.putBoolean('social_notifications_enabled', this.socialNotifications);
      await prefManager.putBoolean('system_announcements_enabled', this.systemAnnouncements);
      
      // 更新远程服务器上的通知设置
      await this.updateServerSettings();
      
      promptAction.showToast({ message: '设置已保存' });
    } catch (error) {
      console.error(`保存设置失败: ${error instanceof Error ? error.message : String(error)}`);
      promptAction.showToast({ message: '保存设置失败' });
    }
  }
  
  async updateServerSettings() {
    try {
      const userId = await getUserId();
      
      if (!userId) return;
      
      await request(
        RequestMethod.PUT,
        '/users/notification-settings',
        {
          userId: userId,
          allNotifications: this.allNotifications,
          taskReminders: this.taskReminders,
          dreamReminders: this.dreamReminders,
          socialNotifications: this.socialNotifications,
          systemAnnouncements: this.systemAnnouncements
        }
      );
    } catch (error) {
      console.error(`更新服务器通知设置失败: ${error instanceof Error ? error.message : String(error)}`);
    }
  }
  
  build() {
    Column() {
      // 顶部导航栏
      TitleBar({ title: '通知设置' })
      
      // 设置选项
      List() {
        // 总开关
        ListItem() {
          Row() {
            Text('接收所有通知')
              .fontSize(16)
              .fontWeight(FontWeight.Medium)
              .layoutWeight(1)
            
            Toggle({ type: ToggleType.Switch, isOn: this.allNotifications })
              .onChange((isOn: boolean) => {
                this.allNotifications = isOn;
              })
          }
          .width('100%')
          .height(56)
          .padding({ left: 16, right: 16 })
        }
        .backgroundColor(Color.White)
        .borderRadius(8)
        
        // 任务提醒
        ListItem() {
          Row() {
            Text('任务截止日期提醒')
              .fontSize(16)
              .fontWeight(FontWeight.Medium)
              .layoutWeight(1)
            
            Toggle({ type: ToggleType.Switch, isOn: this.taskReminders })
              .onChange((isOn: boolean) => {
                this.taskReminders = isOn;
              })
              .enabled(this.allNotifications)
          }
          .width('100%')
          .height(56)
          .padding({ left: 16, right: 16 })
          .opacity(this.allNotifications ? 1.0 : 0.6)
        }
        .backgroundColor(Color.White)
        .borderRadius(8)
        
        // 梦想提醒
        ListItem() {
          Row() {
            Text('梦想目标日期提醒')
              .fontSize(16)
              .fontWeight(FontWeight.Medium)
              .layoutWeight(1)
            
            Toggle({ type: ToggleType.Switch, isOn: this.dreamReminders })
              .onChange((isOn: boolean) => {
                this.dreamReminders = isOn;
              })
              .enabled(this.allNotifications)
          }
          .width('100%')
          .height(56)
          .padding({ left: 16, right: 16 })
          .opacity(this.allNotifications ? 1.0 : 0.6)
        }
        .backgroundColor(Color.White)
        .borderRadius(8)
        
        // 社区通知
        ListItem() {
          Row() {
            Text('社区互动通知')
              .fontSize(16)
              .fontWeight(FontWeight.Medium)
              .layoutWeight(1)
            
            Toggle({ type: ToggleType.Switch, isOn: this.socialNotifications })
              .onChange((isOn: boolean) => {
                this.socialNotifications = isOn;
              })
              .enabled(this.allNotifications)
          }
          .width('100%')
          .height(56)
          .padding({ left: 16, right: 16 })
          .opacity(this.allNotifications ? 1.0 : 0.6)
        }
        .backgroundColor(Color.White)
        .borderRadius(8)
        
        // 系统公告
        ListItem() {
          Row() {
            Text('系统公告')
              .fontSize(16)
              .fontWeight(FontWeight.Medium)
              .layoutWeight(1)
            
            Toggle({ type: ToggleType.Switch, isOn: this.systemAnnouncements })
              .onChange((isOn: boolean) => {
                this.systemAnnouncements = isOn;
              })
              .enabled(this.allNotifications)
          }
          .width('100%')
          .height(56)
          .padding({ left: 16, right: 16 })
          .opacity(this.allNotifications ? 1.0 : 0.6)
        }
        .backgroundColor(Color.White)
        .borderRadius(8)
        
        // 通知权限说明
        ListItem() {
          Column() {
            Text('注意事项')
              .fontSize(16)
              .fontWeight(FontWeight.Medium)
              .alignSelf(ItemAlign.Start)
              .margin({ top: 12, bottom: 8 })
            
            Text('1. 要接收通知,请确保在系统设置中允许"梦想生活规划师"发送通知\n2. 任务和梦想的提醒取决于您设置的截止日期\n3. 关闭通知可能导致您错过重要提醒')
              .fontSize(14)
              .fontColor('#666666')
              .margin({ bottom: 12 })
          }
          .width('100%')
          .padding({ left: 16, right: 16 })
        }
        .backgroundColor(Color.White)
        .borderRadius(8)
        .margin({ top: 16 })
      }
      .divider({ strokeWidth: 1, color: '#F0F0F0' })
      .listDirection(Axis.Vertical)
      .margin({ top: 16 })
      .layoutWeight(1)
      
      // 保存按钮
      Button('保存设置')
        .width('90%')
        .height(50)
        .backgroundColor('#4E6EF2')
        .margin({ top: 24, bottom: 16 })
        .onClick(() => {
          this.saveSettings();
        })
    }
    .width('100%')
    .height('100%')
    .backgroundColor('#F5F5F5')
    .padding({ left: 16, right: 16 })
  }
}

通知应用实例

任务截止通知示例

// 为即将到期的任务创建通知
export async function createUpcomingTaskNotifications(): Promise<void> {
  try {
    // 获取今天和明天的任务
    const upcomingTasks = await getUpcomingTasks(await getUserId(), 2);
    
    if (!upcomingTasks || upcomingTasks.content.length === 0) {
      console.info('没有即将到期的任务');
      return;
    }
    
    const preferences = PreferenceManager.getInstance();
    const taskRemindersEnabled = await preferences.getBoolean('task_reminders_enabled', true);
    
    if (!taskRemindersEnabled) {
      console.info('任务提醒已禁用,跳过创建通知');
      return;
    }
    
    // 获取已经创建的提醒ID列表
    const existingReminderIds = new Set<number>();
    const reminders = await ReminderService.getAllReminders();
    
    reminders.forEach(reminder => {
      if (reminder.notificationId) {
        existingReminderIds.add(reminder.notificationId);
      }
    });
    
    // 为每个即将到期的任务创建提醒
    for (const task of upcomingTasks.content) {
      // 如果已经有提醒,则跳过
      if (existingReminderIds.has(task.id)) {
        continue;
      }
      
      // 创建提醒
      const reminderId = await ReminderService.createTaskDeadlineReminder(task);
      console.info(`为任务创建了提醒: ${task.title}, 提醒ID: ${reminderId}`);
    }
  } catch (error) {
    console.error(`创建任务通知失败: ${error instanceof Error ? error.message : String(error)}`);
  }
}

社区互动通知示例

// 处理社区互动通知
export async function handleSocialInteractionUpdate(notification: SocialNotification): Promise<void> {
  try {
    const preferences = PreferenceManager.getInstance();
    const socialNotificationsEnabled = await preferences.getBoolean('social_notifications_enabled', true);
    
    if (!socialNotificationsEnabled) {
      console.info('社区互动通知已禁用,跳过处理');
      return;
    }
    
    const notificationManager = NotificationManager.getInstance();
    
    // 根据通知类型确定消息内容
    let title = '社区互动';
    let content = '';
    let id = new Date().getTime();
    
    switch (notification.type) {
      case 'comment':
        title = '收到新评论';
        content = `用户 ${notification.senderName} 评论了你的帖子: "${notification.content}"`;
        id = notification.commentId;
        break;
      case 'like':
        title = '收到新点赞';
        content = `用户 ${notification.senderName} 点赞了你的帖子`;
        id = notification.postId + 100000;
        break;
      case 'mention':
        title = '有人@了你';
        content = `用户 ${notification.senderName} 在帖子中提到了你: "${notification.content}"`;
        id = notification.postId + 200000;
        break;
      case 'follow':
        title = '新的关注者';
        content = `用户 ${notification.senderName} 关注了你`;
        id = notification.senderId;
        break;
    }
    
    // 发送通知
    if (notification.imageUrl) {
      const imagePath = await downloadImage(notification.imageUrl);
      if (imagePath) {
        await notificationManager.sendPictureNotification(id, title, content, imagePath);
        return;
      }
    }
    
    await notificationManager.sendBasicNotification(id, title, content);
    console.info(`已发送社区互动通知: ${title}`);
    
  } catch (error) {
    console.error(`处理社区互动通知失败: ${error instanceof Error ? error.message : String(error)}`);
  }
}

通知系统初始化

在应用启动时初始化通知系统:

import { NotificationManager } from '../services/notification/NotificationManager';
import { PushService } from '../services/notification/PushService';

export class Application {
  async onCreate() {
    try {
      // 其他初始化逻辑...
      
      // 初始化通知管理器
      this.initNotificationSystem();
      
      console.info('应用创建成功');
    } catch (error) {
      console.error(`应用创建失败: ${error instanceof Error ? error.message : String(error)}`);
    }
  }
  
  private async initNotificationSystem() {
    try {
      // 获取通知权限
      await this.requestNotificationPermissions();
      
      // 初始化推送服务
      const pushService = PushService.getInstance();
      await pushService.init();
      
      // 创建通知通道
      await this.createNotificationSlots();
      
      console.info('通知系统初始化成功');
    } catch (error) {
      console.error(`通知系统初始化失败: ${error instanceof Error ? error.message : String(error)}`);
    }
  }
  
  private async requestNotificationPermissions() {
    try {
      const permissions = ['ohos.permission.NOTIFICATION_CONTROLLER'];
      await requestPermissionsFromUser(permissions);
      console.info('通知权限请求成功');
    } catch (error) {
      console.error(`请求通知权限失败: ${error instanceof Error ? error.message : String(error)}`);
    }
  }
  
  private async createNotificationSlots() {
    try {
      // 创建通知通道
      const slots = [
        {
          type: notification.SlotType.SOCIAL_COMMUNICATION,
          level: notification.SlotLevel.LEVEL_HIGH
        },
        {
          type: notification.SlotType.SERVICE_INFORMATION,
          level: notification.SlotLevel.LEVEL_DEFAULT
        },
        {
          type: notification.SlotType.CONTENT_INFORMATION,
          level: notification.SlotLevel.LEVEL_LOW
        }
      ];
      
      for (const slot of slots) {
        await notification.createSlot(slot);
      }
      
      console.info('通知通道创建成功');
    } catch (error) {
      console.error(`创建通知通道失败: ${error instanceof Error ? error.message : String(error)}`);
    }
  }
}

通知系统是梦想生活规划师应用的关键功能之一,通过及时提醒和信息通知,确保用户不错过重要的截止日期和社交互动,进而提高用户参与度和应用粘性。系统的智能提醒功能和个性化设置也为用户提供了更好的体验,帮助他们更有效地追踪和完成梦想目标。

Logo

讨论HarmonyOS开发技术,专注于API与组件、DevEco Studio、测试、元服务和应用上架分发等。

更多推荐