HarmonyOS 5.0.0 或以上:实现跨设备消息通信(文本传输 + 控制指令)


📌 场景介绍

跨设备通信是构建分布式应用的基础,适用于:

  • 发送控制指令(如遥控指令、同步状态)

  • 广播消息(群组聊天、协同提醒)

  • 推送数据(内容更新、参数同步)

本篇实现:

  • 使用 @ohos.distributedData 模块建立通信通道

  • 在本设备输入消息,远程设备收到并实时展示

  • 支持双向通信(可扩展至群组)


🧱 页面结构

/entry/src/main/ets
  └── pages/
       └── DistributedMessageDemo.ets     // 跨设备消息通信页面

🧩 DistributedMessageDemo.ets 示例页面

import distributedData from '@ohos.distributedData'

@Entry
@Component
struct DistributedMessageDemo {
  @State input: string = ''
  @State messages: string[] = []
  @State status: string = '📡 正在连接...'

  private kvStore: distributedData.SingleKvStore | undefined

  async aboutToAppear() {
    const context = getContext(this)
    const manager = distributedData.createKVManager({
      context,
      bundleName: 'com.example.harmony',
      userInfo: {
        userId: '0',
        userType: distributedData.UserType.SAME_USER_ID
      }
    })

    this.kvStore = await manager.getSingleKvStore({
      storeId: 'message_channel',
      options: {
        createIfMissing: true,
        encrypt: false,
        backup: false,
        autoSync: true,
        kvStoreType: distributedData.KvStoreType.SINGLE_VERSION
      }
    })

    this.status = '✅ 已连接消息通道'

    // 监听远程设备变更
    this.kvStore.on('dataChange', distributedData.SubscribeType.SUBSCRIBE_TYPE_REMOTE, (changes) => {
      for (let entry of changes.insertEntries) {
        this.messages.push(`📨 来自远程:${entry.value.value}`)
      }
    })
  }

  private async sendMessage() {
    if (!this.input.trim()) return
    const key = `msg_${Date.now()}`
    await this.kvStore?.put(key, this.input)
    this.messages.push(`📤 本地发送:${this.input}`)
    this.input = ''
  }

  build() {
    Column() {
      Text("💬 分布式消息通道").fontSize(22).margin(20)
      Text(`状态:${this.status}`).fontSize(14).fontColor('#666').marginBottom(10)

      TextInput({ placeholder: '输入消息内容', text: this.input, onChange: val => this.input = val })
        .width('100%').marginBottom(10)

      Button("发送消息").onClick(() => this.sendMessage()).marginBottom(20)

      ForEach(this.messages, (msg) => {
        Text(msg).fontSize(14).margin(4)
      })
    }
    .padding(20)
    .height('100%')
    .scrollable(true)
  }
}

✅ 效果说明

  • 多台设备同时运行该页面,即可互相发送和接收消息

  • 通过 KvStore 的分布式同步机制完成传输

  • 支持文本消息,也可扩展为 JSON、指令等结构体


🔧 拓展建议

  • 定义消息格式:type + payload,如 { type: 'cmd', content: 'PLAY' }

  • 封装通信接口层:MessageBus.send() + onReceive()

  • 支持文件协同、实时位置共享等数据同步

  • 可结合页面迁移 + 通信实现“远程控制 + 状态联动”

Logo

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

更多推荐