开发一款多功能智能手表应用,包含运动、健康、消息提醒等功能。不同用户对各类通知的需求和偏好不同,如有的用户希望运动成就通知有特殊音效,有的用户希望重要消息通知能直接在手表屏幕显示详细内容。如何利用鸿蒙系统提供的通知 API,实现通知的声音、震动模式、显示内容等个性化定制,以及如何处理用户与通知的交互(如点击通知进入不同功能界面),以满足不同用户的个性化需求?
开发一款多功能智能手表应用,包含运动、健康、消息提醒等功能。不同用户对各类通知的需求和偏好不同,如有的用户希望运动成就通知有特殊音效,有的用户希望重要消息通知能直接在手表屏幕显示详细内容。如何利用鸿蒙系统提供的通知 API,实现通知的声音、震动模式、显示内容等个性化定制,以及如何处理用户与通知的交互(如点击通知进入不同功能界面),以满足不同用户的个性化需求?
在鸿蒙系统(HarmonyOS)上开发智能手表应用时,利用其通知API实现个性化定制,可按以下步骤进行:
鸿蒙通过 @ohos.notification 模块提供通知能力,核心类为 NotificationRequest 和 NotificationHelper。
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);
}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/ 目录,且需小于32KBfunction getVibration(type: string): Array<number> {
// 振动模式数组: [延迟, 持续, 延迟, 持续...] (单位ms)
const patterns = {
ACHIEVEMENT: [0, 200, 300, 500], // 短-长振动
URGENT_MESSAGE: [0, 1000, 200, 1000] // 强持续振动
};
return patterns[type] || [0, 400];
}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,
... // 简洁显示模板
};
}
}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);
}// 创建专属通知通道
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);通过传感器判断用户状态:
import sensor from '@ohos.sensor';
sensor.on(sensor.SensorId.HEART_RATE, (data) => {
if (data.heartRate > 120) {
// 高心率时不发送非紧急通知
}
});通知优先级:
request.deliveryTime = notification.DeliveryTime.TYPE_NOW; // 即时通知
request.importance = notification.Importance.LEVEL_HIGH; // 高重要性资源限制:
生命周期管理:
// 清理过期通知
notification.cancel(id);用户设置界面:提供可视化配置界面,允许用户:
跨设备同步:通过 @ohos.distributedData 同步用户设置:
const kvManager = createKVManager();
kvManager.on('dataChange', (data) => {
// 手机端修改设置后同步到手表
});无障碍支持:
request.accessibilitySetting = {
spoken: true, // 启用语音播报
vibrate: false // 振动由独立设置控制
};通过上述方案,可满足以下典型场景:
记得在 config.json 声明必要权限:
"reqPermissions": [
{ "name": "ohos.permission.NOTIFICATION_CONTROLLER" },
{ "name": "ohos.permission.VIBRATE" }
]
NotificationBuilderAPI,通过setSound设置运动成就通知的特殊音效,通过setVibratePattern设置震动模式。依据用户偏好,对重要消息通知,使用setContent设置直接显示详细内容。PreferencesAPI 将用户对通知的个性化设置(音效、震动模式、显示内容等)存储在本地,方便应用读取并应用这些设置。Notification.addAction为通知添加点击动作,当用户点击通知时,通过设置不同的Intent,使其进入运动、健康或消息等不同功能界面。PreferencesObserverAPI,实时更新通知设置,确保通知按新的个性化需求展示。