HarmonyOS 5.0.0 或以上:实现跨端协同输入(键盘输入同步 + 表单协作填写)
📌 场景介绍
跨设备表单协同输入,常见于:
-
手机控制平板填写输入框(远程表单)
-
平板输入,手机同步预览(展示演讲)
-
多端编辑同一文档、问卷、备注等
本篇实现:
-
A 端输入文字同步到 B 端显示
-
使用
distributedData
分布式同步输入内容 -
双向实时协同输入(可扩展为多人编辑)
🧱 页面结构
/entry/src/main/ets
└── pages/
└── CollaborativeInputDemo.ets // 协同输入页面(双端可运行)
🧩 CollaborativeInputDemo.ets 示例页面
import distributedData from '@ohos.distributedData'
@Entry
@Component
struct CollaborativeInputDemo {
@State text: string = ''
@State lastSource: string = '本地输入'
private kvStore: distributedData.SingleKvStore | undefined
private key: string = 'collab_input'
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: 'collab_input_store',
options: {
createIfMissing: true,
encrypt: false,
backup: false,
autoSync: true,
kvStoreType: distributedData.KvStoreType.SINGLE_VERSION
}
})
// 监听远端输入变更
this.kvStore.on('dataChange', distributedData.SubscribeType.SUBSCRIBE_TYPE_REMOTE, async (changes) => {
for (const entry of changes.insertEntries) {
if (entry.key === this.key) {
this.text = entry.value.value as string
this.lastSource = '来自远程设备'
}
}
})
// 初始获取一次
try {
const val = await this.kvStore.get(this.key)
if (val) this.text = val
} catch {}
}
private async onInputChange(newVal: string) {
this.text = newVal
this.lastSource = '本地输入'
await this.kvStore?.put(this.key, newVal)
}
build() {
Column() {
Text("📝 分布式协同输入").fontSize(22).margin(20)
TextInput({
placeholder: '请输入内容...',
text: this.text,
onChange: (val) => this.onInputChange(val)
})
.width('100%')
.margin(10)
Text(`当前内容来源:${this.lastSource}`).fontSize(14).fontColor('#888').margin(10)
Text("💡 同时在多端打开本页面,即可同步输入").fontSize(12).fontColor('#999').marginTop(30)
}
.padding(20)
.height('100%')
}
}
✅ 效果说明
-
任一设备输入框变动,另一端立即同步文本内容
-
@ohos.distributedData
实现键值同步 -
实现“跨屏打字”、“远程输入”、“多人编辑”的基础能力
🔧 拓展建议
-
增加用户标识(显示谁正在输入)
-
多段输入状态同步(如正在输入状态)
-
支持同步光标位置、输入时间戳
-
集成富文本编辑组件,构建协同文档或远程答题系统