在基于鸿蒙系统开发智能手表应用时,如何实现设备通知与用户交互的个性化定制?

开发一款多功能智能手表应用,包含运动、健康、消息提醒等功能。不同用户对各类通知的需求和偏好不同,如有的用户希望运动成就通知有特殊音效,有的用户希望重要消息通知能直接在手表屏幕显示详细内容。如何利用鸿蒙系统提供的通知 API,实现通知的声音、震动模式、显示内容等个性化定制,以及如何处理用户与通知的交互(如点击通知进入不同功能界面),以满足不同用户的个性化需求?

阅读 638
avatarAI BotBETA

在鸿蒙系统(HarmonyOS)上开发智能手表应用时,利用其通知API实现个性化定制,可按以下步骤进行:

一、核心通知API使用

鸿蒙通过 @ohos.notification 模块提供通知能力,核心类为 NotificationRequestNotificationHelper

import notification from '@ohos.notification';
import common from '@ohos.app.ability.common';

// 创建基础通知请求
async function sendCustomNotification(context: common.Context, type: string) {
  // 1. 创建NotificationRequest实例
  let request: notification.NotificationRequest = {
    id: generateUniqueId(), // 生成唯一ID
    content: createCustomContent(type), // 根据类型创建内容
    slotType: getSlotType(type), // 获取通知通道类型
    ...
  };

  // 2. 个性化定制点
  request.sound = getCustomSound(type);     // 自定义音效
  request.vibrationStyle = getVibration(type); // 振动模式
  request.actions = createActions(context); // 交互按钮

  // 3. 发布通知
  await notification.publish(request);
}

二、关键定制化实现方案

1. 声音个性化

function getCustomSound(type: string): string {
  switch(type) {
    case 'ACHIEVEMENT':
      return 'resource://raw/achievement_sound.wav'; // 运动成就专用音效
    case 'URGENT_MESSAGE':
      return 'system://alarm_alert'; // 重要消息使用系统警报音
    default:
      return 'system://notification_sound';
  }
}
需注意:将自定义音频文件放入 resources/rawfile/ 目录,且需小于32KB

2. 振动模式定制

function getVibration(type: string): Array<number> {
  // 振动模式数组: [延迟, 持续, 延迟, 持续...] (单位ms)
  const patterns = {
    ACHIEVEMENT: [0, 200, 300, 500],   // 短-长振动
    URGENT_MESSAGE: [0, 1000, 200, 1000] // 强持续振动
  };
  return patterns[type] || [0, 400];
}

3. **内容显示定制

function createCustomContent(type: string): notification.NotificationContent {
  if (type === 'URGENT_MESSAGE') {
    // 重要消息展示完整内容
    return {
      contentType: notification.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT,
      normal: {
        title: "紧急消息",
        text: "您的项目截止时间已提前至今日18点!请立即查看", // 完整内容
        additionalText: "来自工作群"
      }
    };
  } else {
    // 普通通知折叠显示
    return {
      contentType: notification.ContentType.NOTIFICATION_CONTENT_CONVERSATION,
      ... // 简洁显示模板
    };
  }
}

4. **交互行为定制

function createActions(context: common.Context): Array<notification.NotificationAction> {
  return [
    {
      title: "查看详情",
      wantAgent: { // 点击跳转目标
        bundleName: "com.example.watchapp",
        abilityName: "MessageDetailAbility",
        uri: "details://message?id=123" // 携带参数
      }
    },
    {
      title: "快速回复",
      userInput: { // 支持用户直接输入
        inputKey: "quick_reply",
        inputs: ["收到", "稍后回复"]
      }
    }
  ];
}

三、个性化配置存储与读取

使用 @ohos.data.preferences 存储用户偏好:

import dataPreferences from '@ohos.data.preferences';

// 存储设置
async function saveNotificationSettings(userId: string, settings: Object) {
  const pref = await dataPreferences.getPreferences(context, 'notification_settings');
  await pref.put(userId, JSON.stringify(settings));
}

// 读取设置
async function getSettings(userId: string): Promise<Object> {
  const pref = await dataPreferences.getPreferences(context, 'notification_settings');
  const settings = await pref.get(userId, '{}');
  return JSON.parse(settings);
}

四、高级特性实现

1. 分通道管理

// 创建专属通知通道
const healthSlot: notification.NotificationSlot = {
  type: notification.SlotType.SOCIAL_COMMUNICATION,
  level: notification.SlotLevel.LEVEL_HIGH,
  sound: "resource://raw/health_sound.wav",
  vibrationEnabled: true,
  lightEnabled: false // 手表通常无LED灯
};
notification.addSlot(healthSlot);

2. 场景感知通知

通过传感器判断用户状态:

import sensor from '@ohos.sensor';

sensor.on(sensor.SensorId.HEART_RATE, (data) => {
  if (data.heartRate > 120) {
    // 高心率时不发送非紧急通知
  }
});

五、性能优化要点

  1. 通知优先级

    request.deliveryTime = notification.DeliveryTime.TYPE_NOW; // 即时通知
    request.importance = notification.Importance.LEVEL_HIGH; // 高重要性
  2. 资源限制

    • 单条通知不超过1.5KB
    • 图片尺寸≤200x200像素
    • 最多显示3个交互按钮
  3. 生命周期管理

    // 清理过期通知
    notification.cancel(id);

六、最佳实践建议

  1. 用户设置界面:提供可视化配置界面,允许用户:

    • 为不同通知类型选择铃声/振动模式
    • 设置重要消息的详细显示开关
    • 配置快速回复短语
  2. 跨设备同步:通过 @ohos.distributedData 同步用户设置:

    const kvManager = createKVManager();
    kvManager.on('dataChange', (data) => {
      // 手机端修改设置后同步到手表
    });
  3. 无障碍支持

    request.accessibilitySetting = {
      spoken: true, // 启用语音播报
      vibrate: false // 振动由独立设置控制
    };

通过上述方案,可满足以下典型场景:

  • 运动爱好者:成就通知使用激昂音效+高频振动
  • 商务用户:重要邮件显示完整内容+快速回复按钮
  • 健康关注者:心率异常通知触发强提醒并跳转健康页

记得在 config.json 声明必要权限:

"reqPermissions": [
  { "name": "ohos.permission.NOTIFICATION_CONTROLLER" },
  { "name": "ohos.permission.VIBRATE" }
]
1 个回答
  1. 个性化通知设置:使用 NotificationBuilder API,通过 setSound 设置运动成就通知的特殊音效,通过 setVibratePattern 设置震动模式。依据用户偏好,对重要消息通知,使用 setContent 设置直接显示详细内容。
  2. 用户偏好存储:借助鸿蒙的 Preferences API 将用户对通知的个性化设置(音效、震动模式、显示内容等)存储在本地,方便应用读取并应用这些设置。
  3. 通知交互处理:利用 Notification.addAction 为通知添加点击动作,当用户点击通知时,通过设置不同的 Intent,使其进入运动、健康或消息等不同功能界面。
  4. 实时更新应用:当用户修改通知偏好后,通过监听偏好变化事件,利用 PreferencesObserver API,实时更新通知设置,确保通知按新的个性化需求展示。
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进