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()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)
// 其他设备可读取同一文件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'])
}
}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)原子化服务是 HarmonyOS 的独立、免安装服务形态。类似于"小程序"概念,但运行在 HarmonyOS 原生环境中。
特点:
免安装,即用即走
独立分发
服务卡片(Widget)展示
最多 1MB 大小限制(动态加载可突破)
在 DevEco Studio → File → New → Atomic Service Project
模块类型选择 atomicService
// module.json5 配置原子化服务
{
”module”: {
”name”: ”atomicservice”,
”type”: ”atomicService”,
”srcEntry”: ”./ets/AtomicServiceAbility.ets”,
”description”: ”$string:module_desc”,
”deviceTypes”: [”phone”, ”tablet”],
”deliveryWithInstall”: true,
”pages”: ”$profile:main_pages”
}
}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
}
}
]
}// 卡片页面 — 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' }
})
})
}
}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')
}
}// 点击手势
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() })
)
)// 属性动画
@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 } }
])