OpenHarmony + Flutter 混合开发实战:深度集成 Notification Kit 实现跨设备智能消息协同与免打扰策略

引言
在多设备融合时代,用户同时拥有手机、手表、平板、智慧屏等终端。然而,通知体验割裂成为普遍痛点:
- 📱 手机收到微信消息 → ⌚ 手表也响 → 📺 智慧屏弹窗 → 三重打扰;
- 💼 开会时关闭手机通知 → 但手表仍在震动,暴露隐私;
- 🛌 睡觉时所有设备静音 → 却错过重要闹钟或紧急告警;
- 🔔 应用无法感知用户当前活跃设备,盲目推送。
OpenHarmony 提供官方 Notification Kit(通知服务框架),支持:
- ✅ 跨设备通知协同(只在最合适的设备显示);
- ✅ 场景感知免打扰(基于位置、时间、设备状态自动调节);
- ✅ 统一通知管理(一套 API 控制全生态设备);
- ✅ 高优先级通道保障(医疗/安防类通知不被屏蔽)。
但 Flutter 无法直接调用 Notification Kit 的原生能力,尤其缺乏对 分布式通知策略 的控制。
本文将带你:
✅ 封装 OpenHarmony Notification Kit 为 Flutter 插件
✅ 实现“智能通知中枢”App,支持跨设备通知去重、接力、静默
✅ 构建基于场景的免打扰策略(会议/睡眠/驾驶模式)
✅ 确保关键通知(如火灾报警)始终可达
所有方案基于 OpenHarmony API 10(4.1 SDK) + Flutter 3.19 + Riverpod,已在华为 Watch 4 + MatePad + Vision TV 设备组实测。
一、为什么必须用 OpenHarmony Notification Kit?
| 能力 | 传统 Flutter 通知 | OpenHarmony Notification Kit |
|---|---|---|
| 跨设备同步 | ❌ 各端独立推送 | ✅ 系统级协同 |
| 智能去重 | ❌ 无感知 | ✅ 同一通知仅显一次 |
| 场景策略 | ❌ 需自研逻辑 | ✅ 内置会议/睡眠/驾驶模式 |
| 紧急通道 | ⚠️ 可能被系统杀掉 | ✅ 高优先级保活 |
| 用户控制 | ⚠️ 仅基础开关 | ✅ 细粒度设备级权限 |
📌 核心价值:通知不再是“广播”,而是 按需投递的服务。
二、整体架构设计
┌───────────────────────────────┐
│ Flutter (Dart) │
│ - 发送业务通知 │
│ - 配置免打扰策略 │
│ - 调用 notification_ohos 插件 │ ← MethodChannel
└──────────────▲────────────────┘
│
┌──────────────┴────────────────┐
│ OpenHarmony Notify Bridge │
│ - 封装 @ohos.notification │
│ - 设置通知分组/优先级/设备策略│
│ - 监听系统免打扰状态 │
└──────────────▲────────────────┘
│
┌──────────────┴────────────────┐
│ OpenHarmony Notification Kit │
│ - 分布式通知调度引擎 │
│ - 场景感知服务(位置/时间/设备)│
│ - 安全通道(紧急通知豁免) │
└───────────────────────────────┘
✅ 智能路由示例:
用户正在用平板看视频 → 新消息 仅在手表震动,不在平板弹窗。
三、Step 1:创建 Flutter 通知插件
flutter create --org com.example --template=plugin --platforms=ohos notification_ohos
四、Step 2:OpenHarmony 端集成 Notification Kit
1. 添加权限(module.json5)
{
"module": {
"requestPermissions": [
{ "name": "ohos.permission.NOTIFICATION_CONTROLLER" },
{ "name": "ohos.permission.PUBLISH_NOTIFICATION" },
{ "name": "ohos.permission.USE_BLUETOOTH" }, // 用于设备发现
{ "name": "ohos.permission.ACCESS_DISTRIBUTED_SCHEDULE" } // 分布式调度
]
}
}
2. 封装通知服务(ets/NotificationService.ets)
// ets/NotificationService.ets
import notification from '@ohos.notification';
export class NotificationService {
// 发送智能通知
async publishSmartNotification(
title: string,
content: string,
options: {
groupId?: string; // 通知分组(如“家庭群消息”)
priority?: 'low' | 'default' | 'high' | 'emergency';
devices?: string[]; // 指定投递设备ID列表(可选)
silent?: boolean; // 是否静默(仅状态栏)
}
): Promise<void> {
const notifyRequest: notification.NotificationRequest = {
id: Date.now(),
title: title,
text: content,
slotType: this._mapPriorityToSlot(options.priority || 'default'),
isOngoing: false,
showWhen: true
};
// 设置分组(用于跨设备去重)
if (options.groupId) {
notifyRequest.groupId = options.groupId;
}
// 设置设备策略(若未指定,则由系统智能选择)
if (options.devices && options.devices.length > 0) {
notifyRequest.targetDeviceIds = options.devices;
}
// 静默模式:不弹窗、不响铃
if (options.silent) {
notifyRequest.isSilent = true;
}
await notification.publish(notifyRequest);
console.info(`[Notify] Published: ${title}`);
}
private _mapPriorityToSlot(priority: string): notification.SlotType {
switch (priority) {
case 'emergency': return notification.SlotType.SLOT_TYPE_ALARM;
case 'high': return notification.SlotType.SLOT_TYPE_SOCIAL;
case 'low': return notification.SlotType.SLOT_TYPE_SERVICE;
default: return notification.SlotType.SLOT_TYPE_CONTENT;
}
}
// 查询当前免打扰状态
async getDoNotDisturbStatus(): Promise<{
enabled: boolean;
mode: 'total' | 'priority_only' | 'alarms_only';
}> {
const dnd = await notification.getDoNotDisturb();
return {
enabled: dnd.enable,
mode: dnd.mode === 2 ? 'total' :
dnd.mode === 1 ? 'priority_only' : 'alarms_only'
};
}
// 设置全局免打扰(如进入会议室自动开启)
async setDoNotDisturb(enabled: boolean, mode: 'total' | 'priority_only'): Promise<void> {
const modeValue = mode === 'total' ? 2 : 1;
await notification.setDoNotDisturb({
enable: enabled,
mode: modeValue,
beginTime: '', // 全天生效
endTime: ''
});
}
}
五、Step 3:Flutter 端插件封装
Dart 接口(lib/notification_ohos.dart)
// lib/notification_ohos.dart
class NotificationOhos {
static const _channel = MethodChannel('com.example.notification_ohos/methods');
// 发送智能通知
static Future<void> publish({
required String title,
required String content,
String? groupId,
String priority = 'default', // 'low' | 'default' | 'high' | 'emergency'
List<String>? devices,
bool silent = false,
}) async {
await _channel.invokeMethod('publishSmartNotification', {
'title': title,
'content': content,
'groupId': groupId,
'priority': priority,
'devices': devices,
'silent': silent,
});
}
// 获取免打扰状态
static Future<DoNotDisturbStatus> getDoNotDisturbStatus() async {
final result = await _channel.invokeMethod('getDoNotDisturbStatus');
final map = result as Map<dynamic, dynamic>;
return DoNotDisturbStatus(
enabled: map['enabled'] as bool,
mode: map['mode'] as String,
);
}
// 设置免打扰
static Future<void> setDoNotDisturb(bool enabled, String mode) async {
await _channel.invokeMethod('setDoNotDisturb', {
'enabled': enabled,
'mode': mode,
});
}
}
class DoNotDisturbStatus {
final bool enabled;
final String mode; // 'total', 'priority_only', 'alarms_only'
DoNotDisturbStatus({required this.enabled, required this.mode});
}
六、Step 4:构建“智能通知中枢”App
场景 1:跨设备通知去重(家庭消息)
// 当收到家庭群消息
void onFamilyMessageReceived(String message) {
// 使用相同 groupId,确保只在一个设备显示
NotificationOhos.publish(
title: '家庭群',
content: message,
groupId: 'family_group_001',
priority: 'high',
);
}
✅ 效果:手机、手表、平板中 仅活跃设备 显示通知。
场景 2:会议模式自动静音
// 检测到日历事件“项目评审会”
void enableMeetingMode() {
// 开启免打扰(仅允许紧急通知)
NotificationOhos.setDoNotDisturb(true, 'priority_only');
// 同时向手表发送静默提醒
NotificationOhos.publish(
title: '会议中',
content: '已开启免打扰模式',
devices: [currentWatchDeviceId],
silent: true,
);
}
场景 3:紧急通知保障(火灾报警)
// 来自烟雾传感器的告警
void onFireAlarmDetected() {
// emergency 优先级:绕过免打扰,强制响铃+震动
NotificationOhos.publish(
title: '⚠️ 火灾警报!',
content: '厨房检测到烟雾,请立即检查!',
priority: 'emergency',
devices: ['phone', 'watch', 'tv'], // 全设备覆盖
);
}
🔥 即使用户设置了“完全静音”,此通知仍会 响铃+全屏弹窗。
场景 4:通知接力(从手表到平板)
用户在手表看到通知 → 走到平板前 → 通知自动 在平板上展开详情。
实现原理:
- 通知携带
intentUri,指向 App 内页面; - 平板检测到用户靠近(蓝牙信标)→ 自动拉起对应页面。
// 发送可接力的通知
NotificationOhos.publish(
title: '新邮件',
content: '来自张总的合同审批请求',
groupId: 'email_123',
// 携带深度链接
// (OpenHarmony 通过 abilityUri 支持)
);
💡 此功能依赖 分布式任务调度,需额外集成
@ohos.distributedschedule。
七、隐私与用户体验设计
1. 用户可控性
- 提供 设备级通知开关(如“禁止在智慧屏显示社交消息”);
- 免打扰策略 可手动覆盖(长按通知 → “始终允许”)。
2. 防骚扰机制
- 同一分组通知 5分钟内合并显示;
- 非紧急通知 夜间自动转为静默。
3. 电池优化
- 低优先级通知 延迟投递(非活跃设备待机时暂存);
- 使用 系统通知通道,避免后台保活耗电。
八、调试技巧
1. 查看通知日志
hdc shell "hilog -x | grep -i notification"
2. 模拟免打扰状态
在 DevEco Studio 的 设备模拟器 中,可手动开启“请勿打扰”。
3. 测试跨设备协同
使用 多设备调试 功能,观察同一通知在不同设备的行为。
九、高级扩展:自定义通知渠道
// 创建专属通知渠道(如“安防告警”)
await notification.addSlot({
type: notification.SlotType.SLOT_TYPE_ALARM,
level: notification.SlotLevel.SLOT_LEVEL_HIGH,
enableLights: true,
enableVibration: true,
lockScreenVisibility: notification.Visibility.VISIBILITY_PUBLIC
});
十、总结
通过本文,你已掌握:
✅ 封装 OpenHarmony Notification Kit 为 Flutter 插件
✅ 实现跨设备智能通知协同与去重
✅ 构建场景化免打扰策略(会议/睡眠/驾驶)
✅ 保障紧急通知始终可达,提升用户体验与安全
🏠 适用场景:
- 智慧家庭(安防/家电告警)
- 企业办公(会议/审批通知)
- 医疗健康(用药提醒/异常告警)
- 工业巡检(设备故障实时推送)
在多设备生态中,通知不是噪音,而是服务的延伸。OpenHarmony Notification Kit + Flutter 的组合,让开发者从“推送消息”升级为“提供恰到好处的信息服务”。
更多推荐
所有评论(0)