HarmonyOS 5.0.0 或以上:封装分布式通信服务模块(统一发送 + 监听机制)
所有页面可复用同一通信机制,无需重复初始化或绑定。支持消息中转广播给多个业务模块(监听数组)支持本地同步(发出者 UI 同步更新)在分布式应用中,如果每次使用。不同模块间同步逻辑不统一。封装一个全局通信服务类。
·
HarmonyOS 5.0.0 或以上:封装分布式通信服务模块(统一发送 + 接收机制)
📌 场景说明
在分布式应用中,如果每次使用 @ohos.distributedData 时都重新创建 KVManager、注册监听,会导致:
-
代码冗余
-
不同模块间同步逻辑不统一
-
回调难以解耦、复用
本篇目标:
-
封装一个全局通信服务类
DistributedMessenger -
支持
sendMessage(key, value)发送分布式指令 -
支持
onMessage(key, callback)注册分布式监听器
🧱 文件结构
/entry/src/main/ets
├── services/
│ └── DistributedMessenger.ets // ✅ 通用通信模块
└── pages/
└── MessengerDemo.ets // 演示使用方页面
🧩 services/DistributedMessenger.ets
import distributedData from '@ohos.distributedData'
type ListenerMap = {
[key: string]: (value: string) => void
}
export class DistributedMessenger {
private static instance: DistributedMessenger
private kvStore: distributedData.SingleKvStore | undefined
private listeners: ListenerMap = {}
static async getInstance(context: Context): Promise<DistributedMessenger> {
if (!this.instance) {
this.instance = new DistributedMessenger()
await this.instance.init(context)
}
return this.instance
}
private async init(context: Context) {
const manager = distributedData.createKVManager({
context,
bundleName: 'com.example.harmony',
userInfo: {
userId: '0',
userType: distributedData.UserType.SAME_USER_ID
}
})
this.kvStore = await manager.getSingleKvStore({
storeId: 'messenger_store',
options: {
createIfMissing: true,
encrypt: false,
backup: false,
autoSync: true,
kvStoreType: distributedData.KvStoreType.SINGLE_VERSION
}
})
this.kvStore.on('dataChange', distributedData.SubscribeType.SUBSCRIBE_TYPE_REMOTE, (changes) => {
for (const entry of changes.insertEntries) {
const cb = this.listeners[entry.key]
if (cb) cb(entry.value.value as string)
}
})
}
async sendMessage(key: string, value: string) {
await this.kvStore?.put(key, value)
}
onMessage(key: string, callback: (value: string) => void) {
this.listeners[key] = callback
}
}
🧩 pages/MessengerDemo.ets(调用演示)
import { DistributedMessenger } from '../services/DistributedMessenger'
@Entry
@Component
struct MessengerDemo {
@State input: string = ''
@State remoteMsg: string = ''
private messenger?: DistributedMessenger
private key: string = 'sync_text'
async aboutToAppear() {
const context = getContext(this)
this.messenger = await DistributedMessenger.getInstance(context)
this.messenger.onMessage(this.key, (val) => {
this.remoteMsg = `📥 来自远程:${val}`
})
}
private async send() {
await this.messenger?.sendMessage(this.key, this.input)
}
build() {
Column() {
Text("📨 分布式通信封装示例").fontSize(22).margin(20)
TextInput({ text: this.input, placeholder: '输入消息', onChange: val => this.input = val })
.marginBottom(10)
Button("发送消息").onClick(() => this.send()).marginBottom(10)
Text(this.remoteMsg).fontSize(14).fontColor('#666')
}
.padding(20)
.height('100%')
}
}
✅ 效果说明
-
全局唯一
DistributedMessenger管理分布式通信 -
通过
sendMessage()简洁发送,onMessage()注册监听 -
所有页面可复用同一通信机制,无需重复初始化或绑定
🔧 拓展建议
-
支持
offMessage(key)注销监听 -
添加类型支持(如
{ type, data }对象结构) -
支持消息中转广播给多个业务模块(监听数组)
-
支持本地同步(发出者 UI 同步更新)
更多推荐


所有评论(0)