首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >HarmonyOS 分布式能力与原子化服务

HarmonyOS 分布式能力与原子化服务

作者头像
程序猿的栖息地
发布2026-07-07 15:26:51
发布2026-07-07 15:26:51
50
举报

HarmonyOS 分布式能力与原子化服务参考

分布式能力

分布式数据同步

代码语言:javascript
复制
import distributedKVStore from '@ohos.data.distributedKVStore'
 
// 创建分布式 KV 数据库
const kvManagerConfig: distributedKVStore.KVManagerConfig = {
 bundleName: 'com.example.app',
 context: context
}
 
const kvManager = distributedKVStore.createKVManager(kvManagerConfig)
 
const options: distributedKVStore.Options = {
 createIfMissing: true,
 encrypt: false,
 backup: false,
 autoSync: true,
 kvStoreType: distributedKVStore.KVStoreType.SINGLE_VERSION,
 securityLevel: distributedKVStore.SecurityLevel.S2
}
 
const kvStore = await kvManager.getKVStore('distributed_data', options)
 
// 写入数据(自动同步到同组网的其他设备)
await kvStore.put('game_progress', JSON.stringify({ level: 5, score: 1000 }))
 
// 监听数据变更
kvStore.on('dataChange', distributedKVStore.SubscribeType.SUBSCRIBE_TYPE_ALL, (data) => {
 console.info('数据变更: ' + JSON.stringify(data))
})
 
// 手动同步
kvStore.sync(deviceIds, distributedKVStore.SyncMode.PUSH_PULL)
 
// 查询设备列表
import deviceManager from '@ohos.distributedDeviceManager'
const dmInstance = deviceManager.createDeviceManager('com.example.app')
const devices = dmInstance.getAvailableDeviceListSync()

分布式文件

代码语言:javascript
复制
import distributedFile from '@ohos.file.distributedFile'
 
// 分布式文件路径前缀
const distributedPath = context.distributedFilesDir
 
// 写入分布式文件(自动同步)
const file = fileIo.openSync(`${distributedPath}/shared_data.txt`,
 fileIo.OpenMode.CREATE | fileIo.OpenMode.WRITE_ONLY)
fileIo.writeSync(file.fd, '共享内容')
fileIo.closeSync(file)
 
// 其他设备可读取同一文件

设备迁移(流转)

代码语言:javascript
复制
import abilityManager from '@ohos.app.ability.abilityManager'
import continuationManager from '@ohos.app.ability.continuationManager'
 
// 注册流转管理器
const continuationManager.register({
 // 过滤可迁移设备
 deviceFilters: {
 type: continuationManager.DeviceFilterType.ALL
 }
})
 
// 发起迁移
continuationManager.on('deviceSelected', (devices) => {
 // 用户选择了目标设备
 const targetDeviceId = devices[0].deviceId
 this.continueToTarget(targetDeviceId)
})
 
// 在 UIAbility 中实现迁移
export default class EntryAbility extends UIAbility {
 onContinue(wantParam) {
 // 保存迁移数据
 wantParam['data'] = JSON.stringify(this.currentData)
 return AbilityConstant.OnContinueResult.AGREE
 }
 
 onRestoreData(wantParam) {
 // 恢复迁移数据
 this.currentData = JSON.parse(wantParam['data'])
 }
}

跨设备调用(分布式任务调度)

代码语言:javascript
复制
import distributedMissionManager from '@ohos.application.distributedMissionManager'
 
// 启动远程设备的 Ability
import Want from '@ohos.app.ability.Want'
 
const want: Want = {
 deviceId: targetDeviceId, // 目标设备ID
 bundleName: 'com.example.app',
 abilityName: 'RemoteAbility',
 parameters: { action: 'start_remote' }
}
 
// 使用 startAbilityExtension 跨设备启动
context.startAbility(want)

原子化服务(Atomic Service)

厬子化服务概述

原子化服务是 HarmonyOS 的独立、免安装服务形态。类似于"小程序"概念,但运行在 HarmonyOS 原生环境中。

特点:

免安装,即用即走

独立分发

服务卡片(Widget)展示

最多 1MB 大小限制(动态加载可突破)

创建原子化服务

在 DevEco Studio → File → New → Atomic Service Project

模块类型选择 atomicService

代码语言:javascript
复制
// module.json5 配置原子化服务
{
 ”module”: {
 ”name”: ”atomicservice”,
 ”type”: ”atomicService”,
 ”srcEntry”: ”./ets/AtomicServiceAbility.ets”,
 ”description”: ”$string:module_desc”,
 ”deviceTypes”: [”phone”, ”tablet”],
 ”deliveryWithInstall”: true,
 ”pages”: ”$profile:main_pages”
 }
}

服务卡片(Form / Widget)

代码语言:javascript
复制
import formProvider from '@ohos.app.form.formProvider'
 
// 卡片数据更新
const formInfo = {
 formId: '123',
 templateName: 'widget_temp',
 data: {
 title: '今日天气',
 temperature: '26°C',
 weather: '晴'
 }
}
 
formProvider.updateForm(formInfo.formId, formInfo)
 
// 在 module.json5 注册卡片
{
 ”extensionAbilities”: [
 {
 ”name”: ”WeatherFormAbility”,
 ”srcEntry”: ”./ets/form/WeatherFormAbility.ets”,
 ”type”: ”form”,
 ”description”: ”$string:form_desc”,
 ”formConfig”: {
 ”name”: ”weather_widget”,
 ”displayName”: ”天气卡片”,
 ”description”: ”今日天气”,
 ”type”: ”JS”, // JS | ArkTS
 ”supportDimensions”: [”2*2”, ”4*4”],
 ”defaultDimension”: ”2*2”,
 ”updateEnabled”: true,
 ”scheduledUpdateTime”: ”10:30”,
 ”updateDuration”: 1,
 ”formVisibleNotify”: true
 }
 }
 ]
}

ArkTS 卡片开发

代码语言:javascript
复制
// 卡片页面 — widget/pages/WeatherWidget.ets
@Entry
@Component
struct WeatherWidget {
 @State temperature: string = '26°C'
 @State weather: string = '晴'
 
 build() {
 Column() {
 Text('今日天气').fontSize(12).fontColor('#999999')
 Row() {
 Text(this.temperature).fontSize(24).fontWeight(FontWeight.Bold)
 Text(this.weather).fontSize(14).margin({ left: 8 })
 }.margin({ top: 4 })
 }
 .width('100%')
 .height('100%')
 .padding(12)
 .onClick(() => {
 // 点击卡片跳转到完整页面
 postCardAction(this, {
 action: 'router',
 abilityName: 'EntryAbility',
 params: { target: 'weather_detail' }
 })
 })
 }
}

卡片生命周期

代码语言:javascript
复制
import FormExtension from '@ohos.app.form.FormExtension'
 
export default class WeatherFormAbility extends FormExtension {
 // 卡片创建
 onCreate(want) {
 console.info('Form onCreate')
 return {
 formId: want.parameters['ohos.extra.param.key.form_identity'],
 formName: want.parameters['ohos.extra.param.key.form_name'],
 data: { temperature: '26°C', weather: '晴' }
 }
 }
 
 // 卡片更新
 onUpdate(formId) {
 // 获取最新数据并更新卡片
 const newData = this.fetchWeatherData()
 formProvider.updateForm(formId, {
 data: newData
 })
 }
 
 // 卡片销毁
 onDestroy(formId) {
 console.info('Form onDestroy')
 }
}

多模态交互

手势识别

代码语言:javascript
复制
// 点击手势
Text('点击我')
 .gesture(
 TapGesture({ count: 2 }) // 双击
 .onAction((event) => { this.handleDoubleTap() })
 )
 
// 长按手势
Text('长按')
 .gesture(
 LongPressGesture({ repeat: true, duration: 500 })
 .onAction((event) => { this.handleLongPress() })
 .onActionEnd(() => { this.handleLongPressEnd() })
 )
 
// 拖拽手势
Image($r('app.media.drag_item'))
 .gesture(
 PanGesture({ fingers: 1, distance: 5 })
 .onActionStart(() => { this.startDrag() })
 .onActionUpdate((event) => {
 this.offsetX = event.offsetX
 this.offsetY = event.offsetY
 })
 .onActionEnd(() => { this.endDrag() })
 )
 
// 旋转手势
.gesture(
 RotationGesture()
 .onActionBegin((event) => { this.startAngle = event.angle })
 .onActionUpdate((event) => { this.currentAngle = event.angle })
)
 
// 缩放手势
.gesture(
 PinchGesture()
 .onActionBegin((event) => { this.startScale = event.scale })
 .onActionUpdate((event) => { this.currentScale = event.scale })
)
 
// 组合手势
.gesture(
 GestureGroup(GestureMode.Parallel,
 TapGesture().onAction(() => { this.handleTap() }),
 LongPressGesture().onAction(() => { this.handleLongPress() })
 )
)

动画

代码语言:javascript
复制
// 属性动画
@State boxWidth: number = 100
@State boxColor: string = '#007DFF'
 
Column() {
 Column()
 .width(this.boxWidth)
 .height(100)
 .backgroundColor(this.boxColor)
 .animation({ duration: 500, curve: Curve.EaseInOut })
}
Button('变大').onClick(() => { this.boxWidth = 200 })
Button('变色').onClick(() => { this.boxColor = '#FF4400' })
 
// 显式动画
animateTo({ duration: 500, curve: Curve.Spring }, () => {
 this.boxWidth = 200
 this.boxColor = '#FF4400'
})
 
// 转场动画
Column()
 .transition(
 TransitionEffect.OPACITY
 .combine(TransitionEffect.SLIDE)
 .animation({ duration: 300 })
 )
 
// 关键帧动画
keyframeAnimateTo({ duration: 1000, iterations: -1 }, [
 { 0: { width: 100, height: 100 } },
 { 50: { width: 200, height: 200 } },
 { 100: { width: 100, height: 100 } }
])
本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2026-07-06,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 程序猿的栖息地 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • HarmonyOS 分布式能力与原子化服务参考
  • 分布式能力
    • 分布式数据同步
    • 分布式文件
    • 设备迁移(流转)
    • 跨设备调用(分布式任务调度)
  • 原子化服务(Atomic Service)
    • 厬子化服务概述
    • 创建原子化服务
    • 服务卡片(Form / Widget)
    • ArkTS 卡片开发
    • 卡片生命周期
    • 多模态交互
    • 手势识别
    • 动画
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档