鸿蒙分布式能力入门

📅 2025-05-05 · ⏱ 20 分钟 · 进阶

分布式能力是 HarmonyOS 的核心差异化特性。它让多台设备像一台设备一样协同工作,为用户带来无缝的跨设备体验。

一、分布式软总线

分布式软总线是设备间通信的基础,自动发现和连接周边设备。

设备发现

import { distributedDeviceManager } from "@kit.DistributedServiceKit"

async function discoverDevices() {
  try {
    const deviceManager = distributedDeviceManager.createDeviceManager("com.example.myapp")
    const devices = deviceManager.getAvailableDeviceListSync()

    devices.forEach(device => {
      console.log(`设备: ${device.deviceName}`)
      console.log(`类型: ${device.deviceType}`)
      console.log(`ID: ${device.deviceId}`)
    })

    return devices
  } catch (err) {
    console.error("设备发现失败: " + JSON.stringify(err))
  }
}

设备类型

deviceType设备
phone手机
tablet平板
2in1折叠屏/二合一设备
tv智慧屏
wearable手表

二、分布式数据对象

分布式数据对象可以实现在多台设备间自动同步数据,就像操作本地变量一样简单。

import { distributedDataObject } from "@kit.ArkData"

// 创建分布式数据对象
interface GameData {
  score: number
  level: number
  playerName: string
}

@Entry
@Component
struct DistributedDemo {
  @State score: number = 0
  @State syncStatus: string = "未同步"
  private dataObject?: distributedDataObject.DataObject
n  aboutToAppear() {
    this.initDistributedData()
  }

  async initDistributedData() {
    const context = getContext(this)
    const gameData: GameData = { score: 0, level: 1, playerName: "Player1" }

    // 创建数据对象
    this.dataObject = distributedDataObject.create(context, gameData)

    // 监听数据变化
    this.dataObject.on("change", (sessionId, fields) => {
      console.log("数据变化: " + JSON.stringify(fields))
      this.syncStatus = "已同步"
    })

    // 生成会话 ID 供其他设备加入
    const sessionId = this.dataObject.generateSessionId()
    console.log("会话 ID: " + sessionId)
  }

  build() {
    Column() {
      Text("分数: " + this.score).fontSize(24)
      Text("同步状态: " + this.syncStatus).fontSize(14).fontColor("#999")

      Button("加分")
        .onClick(() => {
          if (this.dataObject) {
            this.dataObject.set("score", ++this.score)
          }
        })
    }
    .padding(20)
  }
}

三、跨设备迁移

让应用从一台设备无缝迁移到另一台设备继续使用。

import { continuationManager } from "@kit.AbilityKit"

// 注册迁移回调
async function registerContinuation() {
  continuationManager.on("continueState", (data) => {
    if (data.reason === "CONTINUE_REASON_SWITCH") {
      console.log("应用正在迁移到其他设备")
    }
  })
}

// 发起迁移
async function migrateToDevice(deviceId: string) {
  try {
    await continuationManager.startContinuationDevice(deviceId)
    console.log("迁移成功")
  } catch (err) {
    console.error("迁移失败: " + JSON.stringify(err))
  }
}

// 保存迁移数据
async function onSaveContinueState(wantParams: Record) {
  // 将当前页面状态保存到 wantParams 中
  wantParams["currentPage"] = "detail"
  wantParams["scrollPosition"] = 150
}

四、适用场景

五、开发注意事项