管理中心
我的
您当前正在浏览新版开发者文档中心,目录分类和层级有所调整。点击左侧当前文档分类名称前的“☰”图标,可切换文档分类。 了解新版目录
最佳实践创新特性开发技术创新互动卡片开发实践

互动卡片开发实践

概述

场景动效类型互动卡片(本文后续简称为互动卡片),是一种支持动态动画和实时交互的卡片形态,区别于动态卡片,互动卡片能够在用户触发时展示流畅的帧动画、3D变换效果,并支持陀螺仪等传感器交互,还能将动效渲染区域扩展到卡片自身边界之外,营造“破框”效果。互动卡片包含非激活态和激活态两种状态:非激活态下,卡片与普通卡片行为一致,由FormExtensionAbility管理;激活态下,由LiveFormExtensionAbility加载动态UI页面展示动画和交互内容。详细信息请参考场景动效类型互动卡片开发指导

说明

互动卡片包含趣味交互类型互动卡片和场景动效类型互动卡片两种类型,本文仅介绍场景动效类型互动卡片。

在阅读本文之前,建议先了解HarmonyOS卡片开发基础、ArkTS语法和UIAbility组件生命周期,并准备好DevEco Studio 6.1.0 Release及以上版本的开发环境。

场景介绍

本项目包含四种互动卡片,分别对应不同的交互场景和体验效果:

展开

卡片名称

用途

实现方式

睡眠卡片

状态提醒

帧动画、点击切换

快递卡片

动态呈现用户快递状态,当前演示状态为“运输中”

帧动画、陀螺仪交互

运动卡片

开始运动、结束运动

帧动画、点击交互

音乐卡片

切歌、暂停等音频控制

Canvas自绘制、点击交互

睡眠卡片

触发方式

点击。

体验及交互

点击卡片触发憨憨起床动画,三叶草旋转,气球飘出卡片边界,憨憨从睡姿变为醒姿,动画结束后卡片状态更新为“按时起床”。

效果预览

快递卡片

触发方式

点击、摇一摇。

体验及交互

点击卡片或摇动设备激活卡片后,倾斜手机驱动憨憨沿路线跑动——向右倾斜憨憨向右移动并缩小(近→远透视),向左倾斜憨憨向左移动并放大(远→近透视)。

效果预览

运动卡片

触发方式

点击。

体验及交互

  • 开始运动:点击“开始运动”触发憨憨拉伸运动动画。
  • 结束运动:点击“结束运动”触发庆祝动画并显示卡路里计数,从0逐步增长到300kcal。

效果预览

  • 开始运动

  • 结束运动

音乐卡片

触发方式

点击。

体验及交互

  • 播放:播放音乐时憨憨跳舞、专辑封面旋转。
  • 切歌:切歌时憨憨出框取专辑进行替换。

效果预览

  • 播放:

  • 切歌:

整体方案

互动卡片以动态卡片作为入口,通过form_config.json中的sceneAnimationParams标签配置关联LiveFormExtensionAbility。用户触发激活(点击或摇一摇)后,系统根据sceneAnimationParams.abilityName激活对应的LiveFormExtensionAbility实例,调用onLiveFormCreate方法加载动态UI页面,展示动画和交互内容。详见互动卡片实现原理。

动态卡片创建

动态卡片是互动卡片的入口,开发者需按照创建ArkTS卡片流程进行创建。

互动卡片配置及触发方法

互动卡片的配置和触发涉及三个关键部分:

1. 在module.json5的extensionAbilities中声明LiveFormExtensionAbility,type设置为liveForm,声明为互动卡片。

收起
自动换行
深色代码主题
复制
  1. {
  2. "name": "DeliveryLiveCardAbility",
  3. "srcEntry": "./ets/livecardability/DeliveryLiveCardAbility.ets",
  4. "type": "liveForm",
  5. "exported": false
  6. },

2. 在form_config.json中通过sceneAnimationParams.abilityName指定触发动画时激活的LiveFormExtensionAbility名称。

3. 触发方式

互动卡片支持两种触发方式:

  • 点击触发:用户点击卡片时,卡片通过postCardAction(MESSAGE)发送requestOverflow消息到FormExtensionAbility,FormExtensionAbility调用formProvider.requestOverflow激活互动卡片。
  • 摇一摇触发:在form_config.json中通过sceneAnimationParams.triggerTypes增加"shake"字段,系统自动监听摇动事件并激活LiveFormExtensionAbility。

摇一摇触发流程:

展开

步骤

操作

说明

1

用户摇动设备

系统识别摇一摇事件

2

查找sceneAnimationParams.triggerTypes配置的卡片

匹配支持的卡片

3

读取sceneAnimationParams.abilityName

获取LiveFormExtensionAbility名称

4

触发FormExtensionAbility的onUpdateForm方法

系统将摇一摇事件发送给卡片

5

调用requestOverflow请求激活互动卡片

FormExtensionAbility中主动拉起激活互动卡片

6

创建LiveFormExtensionAbility实例

系统自动创建

7

调用onLiveFormCreate方法

加载动画UI

说明

摇一摇激活互动卡片能力仅在HarmonyOS 7.0及以上版本触发。

通信方式

动态卡片、应用和互动卡片三者之间存在多种通信方式,不同通信方向使用不同的API和数据传递机制:

展开

通信方向

方式

核心API

说明

动态卡片 → 应用(EntryAbility)

页面跳转

postCardAction(ROUTER)

点击卡片跳转到应用页面

动态卡片 → 应用(EntryAbility)

方法调用

postCardAction(CALL)

通过Callee监听调用应用方法

动态卡片 → FormExtensionAbility

发送消息

postCardAction(MESSAGE)

通过FormExtensionAbility.onFormEvent接收处理消息

应用 → 动态卡片

数据推送

formProvider.updateForm + formBindingData

键值对自动映射到@LocalStorageProp

应用 → 互动卡片

数据持久化

@ohos.data.preferences (用户首选项)/ @ohos.data.relationalStore (关系型数据库) / 文件存储

跨进程通信,LiveFormExtensionAbility读取

互动卡片内部

共享存储

LocalStorage

同一进程内,LiveFormExtensionAbility→ 互动卡片UI

互动卡片 → 动态卡片

数据回推

formProvider.updateForm

互动卡片状态变化回推到动态卡片

各卡片使用的通信方式如下:

睡眠卡片:使用ROUTER跳转页面(CloverPage、SleepReport)、MESSAGE触发出框动画、formProvider.updateForm回推isSleep状态到动态卡片。LocalStorage在互动卡片内部传递formRect、borderRadius等初始数据。

音乐卡片:使用CALL调用播控方法(播放/暂停/切歌/收藏)、ROUTER跳转页面(MusicPage)、MESSAGE触发出框动画并携带triggerAction上下文。应用与互动卡片间通过RDB存储歌曲列表和收藏状态、文件存储触发动作上下文和当前歌曲,实现跨进程数据同步。应用在切歌、播放状态改变时,通过formProvider.updateForm将歌曲信息同步到所有动态卡片中。

运动卡片:使用CALL调用运动控制方法(开始/结束/重置)、ROUTER跳转页面(ExercisePage)、MESSAGE触发出框动画。应用与互动卡片间通过文件存储持久化运动状态,互动卡片通过formProvider.updateForm回推卡路里数据到动态卡片。

快递卡片:使用ROUTER跳转页面(DeliveryPage)、MESSAGE触发出框动画。互动卡片内部通过LocalStorage传递formRect、borderRadius等初始数据。

快递卡片详细开发步骤

场景描述

以快递卡片为例,演示完整的互动卡片开发流程。快递卡片需要实现点击触发出框动画、陀螺仪交互驱动憨憨移动、摇一摇激活等功能。效果如下:

实现原理

快递卡片涉及动态卡片UI、LiveFormExtensionAbility、数据通信、陀螺仪交互四个核心模块。动态卡片展示背景和憨憨;LiveFormExtensionAbility加载动画UI并传递卡片尺寸信息;通信机制实现点击触发动画和页面跳转;陀螺仪交互实现憨憨实时响应设备倾斜。

开发步骤

配置卡片和Ability

  1. 配置form_config.json:定义快递卡片基本信息、配置LiveFormExtensionAbility和摇一摇支持。
    收起
    自动换行
    深色代码主题
    复制
    1. {
    2. "name": "DeliveryCard",
    3. "displayName": "$string:DeliveryCard",
    4. "description": "$string:DeliveryCardDes",
    5. "src": "./ets/widget/pages/DeliveryCard.ets",
    6. "uiSyntax": "arkts",
    7. "defaultDimension": "2*2",
    8. "supportDimensions": [
    9. "2*2"
    10. ],
    11. "sceneAnimationParams": {
    12. "abilityName": "DeliveryLiveCardAbility",
    13. "triggerTypes": ["shake"]
    14. }
    15. }
  2. 声明DeliveryLiveCardAbility:在module.json5中声明LiveFormExtensionAbility扩展能力。
    收起
    自动换行
    深色代码主题
    复制
    1. {
    2. "name": "DeliveryLiveCardAbility",
    3. "srcEntry": "./ets/livecardability/DeliveryLiveCardAbility.ets",
    4. "type": "liveForm",
    5. "exported": false
    6. },

实现动态卡片UI

创建DeliveryCard页面:展示背景图片、憨憨图片,点击触发动画激活。
收起
自动换行
深色代码主题
复制
  1. let storageUpdateCall = new LocalStorage();
  2. @Entry(storageUpdateCall)
  3. @Component
  4. struct DeliveryCard {
  5. @LocalStorageProp('formWidth') formWidth: number = 0;
  6. @LocalStorageProp('formHeight') formHeight: number = 0;
  7. build() {
  8. RelativeContainer() {
  9. Image($rawfile('delivery/background.png'))
  10. .objectFit(ImageFit.Contain)
  11. .width('100%')
  12. .height('100%')
  13. .aspectRatio(1);
  14. Image($rawfile('delivery/fuzzball.png'))
  15. .objectFit(ImageFit.Contain)
  16. .width('145%')
  17. .height('145%')
  18. .offset({
  19. x: `-22.5%`,
  20. y: `-22.5%`
  21. });
  22. Row() {
  23. Image($r('app.media.delivery_box'))
  24. .objectFit(ImageFit.Contain)
  25. .width(this.formWidth * 0.2 + 'px')
  26. .height(this.formHeight * 0.2 + 'px');
  27. Text($r('app.string.delivery_in_transit'))
  28. .fontSize('21.55f')
  29. .fontColor('#646166')
  30. .fontFamily('HarmonyOS Scans SC');
  31. }
  32. .justifyContent(FlexAlign.SpaceEvenly)
  33. .alignRules({
  34. middle: { anchor: '__container__', align: HorizontalAlign.Center },
  35. bottom: { anchor: '__container__', align: VerticalAlign.Bottom }
  36. })
  37. .backgroundColor('#BFFFFFFF')
  38. .width(this.formWidth * 0.830 + 'px')
  39. .height(this.formHeight * 0.205 + 'px')
  40. .margin({ bottom: this.formHeight * 0.082 + 'px' })
  41. .borderRadius('9%');
  42. Stack()
  43. .width('100%')
  44. .height('30%')
  45. .onClick(() => {
  46. ActionUtils.jumpAppPage(this, 'DeliveryPage');
  47. })
  48. .alignRules({
  49. left: { anchor: '__container__', align: HorizontalAlign.Start },
  50. bottom: { anchor: '__container__', align: VerticalAlign.Bottom }
  51. });
  52. }
  53. .width('100%')
  54. .height('100%')
  55. .onClick(() => {
  56. ActionUtils.requestOverFlow(this, LiveCardScale.DELIVERY_WIDTH,
  57. LiveCardScale.DELIVERY_HEIGHT, LIVE_CARD_DURATION);
  58. });
  59. }
  60. }

实现LiveFormExtensionAbility

创建DeliveryLiveCardAbility:在onLiveFormCreate中存储卡片信息并加载动态UI。
收起
自动换行
深色代码主题
复制
  1. onLiveFormCreate(liveFormInfo: LiveFormInfo, session: UIExtensionContentSession): void {
  2. let storage: LocalStorage = new LocalStorage();
  3. storage.setOrCreate('context', this.context);
  4. storage.setOrCreate('session', session);
  5. let formId: string = liveFormInfo.formId;
  6. storage.setOrCreate('formId', formId);
  7. let borderRadius: number = liveFormInfo.borderRadius;
  8. storage.setOrCreate('borderRadius', borderRadius);
  9. let formRect: formInfo.Rect = liveFormInfo.rect;
  10. storage.setOrCreate('formRect', formRect);
  11. try {
  12. session.loadContent('livecardability/pages/DeliveryLiveCard', storage);
  13. } catch (error) {
  14. Logger.error(TAG, `session.loadContent error`);
  15. }
  16. }

实现互动卡片激活流程

  1. 处理message类型消息:在FormExtensionAbility的onFormEvent中接收requestOverflow消息,激活互动卡片动画。
    收起
    自动换行
    深色代码主题
    复制
    1. onFormEvent(formId: string, message: string): void {
    2. const params: Record<string, Object> = JSON.parse(message);
    3. if (!params || typeof params.message !== 'string') {
    4. return;
    5. }
    6. let shortMessage: string = params.message as string;
    7. if (shortMessage === 'requestOverflow') {
    8. let widthRatio: number = Math.min(Math.max(params.widthRatio as number || 0, 0), LIVE_CARD_RATIO);
    9. let heightRatio: number = Math.min(Math.max(params.heightRatio as number || 0, 0), LIVE_CARD_RATIO);
    10. let duration: number = Math.min(Math.max(params.duration as number || 0, 0), LIVE_CARD_DURATION);
    11. // ...
    12. this.requestOverflow(formId, widthRatio, heightRatio, duration);
    13. return;
    14. } else if (shortMessage === 'updateRequestOverflowState') {
    15. updateRequestOverFlowState(formId, true);
    16. }
    17. }
  2. 请求激活互动卡片。
    收起
    自动换行
    深色代码主题
    复制
    1. private async requestOverflow(formId: string, widthRatio: number, heightRatio: number,
    2. duration: number): Promise<void> {
    3. try {
    4. let formRect: formInfo.Rect = await formProvider.getFormRect(formId);
    5. // ...
    6. if (formRect.width <= 0 || formRect.height <= 0) {
    7. return;
    8. }
    9. let cardWidth = formRect.width * widthRatio;
    10. let cardHeight = formRect.height * heightRatio;
    11. let leftOffset = (formRect.width - cardWidth) / 2;
    12. let topOffset = (formRect.height - cardHeight) / 2;
    13. formProvider.requestOverflow(formId, {
    14. area: {
    15. left: leftOffset,
    16. top: topOffset,
    17. width: cardWidth,
    18. height: cardHeight
    19. },
    20. duration: duration
    21. }).catch((e: BusinessError) => {
    22. Logger.error(TAG, `requestOverflow error, code: ${e.code} message: ${e.message}`);
    23. }).finally(() => {
    24. const timeoutId = setTimeout(() => {
    25. updateRequestOverFlowState(formId, false);
    26. clearTimeout(timeoutId);
    27. }, 500)
    28. });
    29. } catch (error) {
    30. // ...
    31. }
    32. }

实现互动卡片动画UI

  1. 创建DeliveryLiveCard页面。
    收起
    自动换行
    深色代码主题
    复制
    1. @Entry({ useSharedStorage: true })
    2. @Component
    3. struct DeliveryLiveCard {
    4. @LocalStorageProp('formRect') rect?: formInfo.Rect = undefined;
    5. @LocalStorageProp('borderRadius') radius: number = 0;
    6. // ...
    7. @State ballSize: number = 0.3;
    8. @State ballTranslateX: number = 150;
    9. @State ballY: number = 0;
    10. // ...
    11. build() {
    12. Stack({ alignContent: Alignment.TopStart }) {
    13. Image($rawfile('delivery/background.png'))
    14. .borderRadius(this.radius)
    15. .width(this.rect?.width || 0)
    16. .height(this.rect?.height || 0)
    17. .margin({
    18. top: this.rect?.top,
    19. left: this.rect?.left
    20. });
    21. Stack() {
    22. Image(this.img)
    23. .width('100%')
    24. .height('100%')
    25. .scale({
    26. x: this.ballSize,
    27. y: this.ballSize
    28. })
    29. .translate({
    30. x: this.ballTranslateX,
    31. y: this.ballY
    32. })
    33. // ...
    34. }
    35. // ...
    36. }
    37. .onClick(() => {
    38. formProvider.cancelOverflow(this.formId).catch(() => {
    39. Logger.error(TAG, `cancelOverflow error`);
    40. });
    41. })
    42. .width('100%')
    43. .height('100%');
    44. }
    45. // ...
    46. }
  2. 订阅陀螺仪数据。
    收起
    自动换行
    深色代码主题
    复制
    1. subscribeGyroscope() {
    2. GyroscopeUtil.subscribe((data: GyroscopeData) => {
    3. this.gyroTranslateX = Math.max(-this.maxGyroValue, Math.min(this.maxGyroValue, data.y));
    4. this.gyroTranslateY = Math.max(-this.maxGyroValue, Math.min(this.maxGyroValue, data.x));
    5. this.gyroTranslateZ = Math.max(-this.maxGyroValue, Math.min(this.maxGyroValue, data.z));
    6. this.gyroMethod();
    7. });
    8. }
  3. 更新憨憨位置。
    收起
    自动换行
    深色代码主题
    复制
    1. private updateBallPosition(): void {
    2. const normalizedValue = this.accumulatedY;
    3. // ...
    4. if (normalizedValue > this.threshold) {
    5. const t = Math.min((normalizedValue - this.threshold) / (1 - this.threshold), 1);
    6. this.targetBallX = t * 100; // towards right
    7. this.targetBallSize = 1 - t * 0.35;
    8. // ...
    9. } else if (normalizedValue < -this.threshold) {
    10. const t = Math.min((-normalizedValue - this.threshold) / (1 - this.threshold), 1);
    11. this.targetBallX = -t * 50; // towards left
    12. this.targetBallSize = 1 + t * 0.3;
    13. // ...
    14. } else {
    15. this.targetBallX = 0;
    16. this.targetBallSize = 1;
    17. // ...
    18. }
    19. // ...
    20. }
  4. 触发动画变化。
    收起
    自动换行
    深色代码主题
    复制
    1. private animateBall(duration: number = 100): void {
    2. if (duration > 0) {
    3. this.getUIContext().animateTo({
    4. duration: duration,
    5. curve: Curve.Linear
    6. }, () => {
    7. this.ballTranslateX = this.targetBallX;
    8. this.ballSize = this.targetBallSize;
    9. });
    10. } else {
    11. this.ballTranslateX = this.targetBallX;
    12. this.ballSize = this.targetBallSize;
    13. }
    14. }

常见问题

互动卡片动画白屏

问题描述

点击卡片触发动画后,互动卡片UI显示白屏,动画内容未正常加载。

可能根因

在onLiveFormCreate中进行了异步操作后才调用loadContent,导致UI加载时机错误。loadContent必须在onLiveFormCreate中同步调用,异步数据加载应在loadContent之后执行。

解决方案

调整代码顺序,先同步调用loadContent加载UI,再执行异步数据获取操作:

  1. 在onLiveFormCreate中先创建LocalStorage并调用session.loadContent加载UI页面。
  2. loadContent必须在onLiveFormCreate中同步调用,确保UI框架在正确时机加载页面。
  3. 异步数据获取操作(如网络请求、数据库读取等)应在loadContent之后执行,避免阻塞UI加载。
    收起
    自动换行
    深色代码主题
    复制
    1. onLiveFormCreate(liveFormInfo: LiveFormInfo, session: UIExtensionContentSession): void {
    2. let storage: LocalStorage = new LocalStorage();
    3. storage.setOrCreate('context', this.context);
    4. storage.setOrCreate('session', session);
    5. let formId: string = liveFormInfo.formId;
    6. storage.setOrCreate('formId', formId);
    7. let borderRadius: number = liveFormInfo.borderRadius;
    8. storage.setOrCreate('borderRadius', borderRadius);
    9. let formRect: formInfo.Rect = liveFormInfo.rect;
    10. storage.setOrCreate('formRect', formRect);
    11. try {
    12. session.loadContent('livecardability/pages/ExerciseLiveCard', storage);
    13. } catch (error) {
    14. Logger.error(TAG, 'loadContent error');
    15. }
    16. try {
    17. let savedState = ExerciseFileStore.readExerciseState(this.context);
    18. if (savedState === undefined) {
    19. savedState = ExerciseState.NOT_STARTED;
    20. }
    21. Logger.info(TAG, `savedState: ${savedState}`)
    22. storage.setOrCreate('exerciseState', savedState);
    23. } catch (err) {
    24. Logger.error(TAG, `readExerciseState error, code is ${err.code}, message is ${err.message}`);
    25. storage.setOrCreate('exerciseState', ExerciseState.NOT_STARTED);
    26. }
    27. }

动画切换不平滑

问题描述

陀螺仪控制憨憨移动时,动画切换出现卡顿或跳跃。

可能根因

更新频率和位移距离设置不合理,连续两段动画位移距离差距过大。

解决方案

优化动画参数配置,控制合理的过渡时间及位移距离:

收起
自动换行
深色代码主题
复制
  1. private animateBall(duration: number = 100): void {
  2. if (duration > 0) {
  3. this.getUIContext().animateTo({
  4. duration: duration,
  5. curve: Curve.Linear
  6. }, () => {
  7. this.ballTranslateX = this.targetBallX;
  8. this.ballSize = this.targetBallSize;
  9. });
  10. } else {
  11. this.ballTranslateX = this.targetBallX;
  12. this.ballSize = this.targetBallSize;
  13. }
  14. }

示例代码