ArkTS与鸿蒙应用开发(6)

卡片服务:打造鸿蒙桌面的健康数据卡片

随着项目的深入,我开始探索鸿蒙系统的特色功能——服务卡片。这是一种可以放置在桌面上的小组件,为用户提供快速访问和信息展示。本文分享我在实现健康数据卡片过程中的经验。

卡片的基本结构

在鸿蒙系统中,卡片是通过FormExtensionAbility实现的,它有自己独立的生命周期和UI结构。

typescript

Apply to UserDataCard...

import { formBindingData, FormExtensionAbility, formInfo, formProvider } from '@kit.FormKit';

import { Want } from '@kit.AbilityKit';

import dataPreferences from '@ohos.data.preferences';

import common from '@ohos.app.ability.common';

export default class HealthDataFormAbility extends FormExtensionAbility {

  // 卡片被添加时触发

  onAddForm(want: Want) {

    // 获取卡片ID

    const formId = want.parameters?.[formInfo.FormParam.IDENTITY_KEY]?.toString() || '';

    

    // 返回默认数据

    const defaultData = this.getDefaultFormData(formId);

    

    // 异步更新卡片数据

    this.updateCardData(formId);

    

    return formBindingData.createFormBindingData(defaultData);

  }

  

  // 卡片更新时触发

  onUpdateForm(formId: string) {

    this.updateCardData(formId);

  }

  

  // 处理卡片事件

  onFormEvent(formId: string, message: string) {

    // 处理刷新等事件

    if (message === 'refresh') {

      this.updateCardData(formId);

    }

  }

}

卡片UI设计

卡片的UI设计需要简洁明了,同时提供足够的信息和交互能力。在我的健康卡片中,我采用了渐变背景和科技感设计。

typescript

Apply to UserDataCard...

@Entry(localStorage)

@Component

struct UserDataCard {

  @LocalStorageProp('isLoggedIn') isLoggedIn: boolean = false;

  @LocalStorageProp('userName') userName: string = '';

  @LocalStorageProp('userHeight') userHeight: string = '0';

  @LocalStorageProp('weight') weight: string = '0';

  

  build() {

    Stack() {

      // 背景渐变层

      Column()

        .width('100%')

        .height('100%')

        .linearGradient({

          angle: 135,

          colors: [['#0057B8', 0.0], ['#0080FF', 0.5], ['#00A3FF', 1.0]]

        })

        .borderRadius(24)

      

      // 内容区域

      Column() {

        if (this.isLoggedIn) {

          // 已登录状态 - 显示用户数据

          this.buildUserDataView()

        } else {

          // 未登录状态 - 显示登录提示

          this.buildLoginPromptView()

        }

      }

      .padding(16)

    }

    .width('100%')

    .height('100%')

  }

  

  @Builder

  buildUserDataView() {

    // 用户数据展示

  }

  

  @Builder

  buildLoginPromptView() {

    // 登录提示

  }

}

卡片数据更新

卡片数据的更新是一个关键环节,我通过检查用户登录状态和获取最新的健康数据来保持卡片内容的实时性。

typescript

Apply to UserDataCard...

private async updateCardData(formId: string) {

  try {

    // 检查登录状态

    const isLoggedIn = await this.checkLoginStatus();

    

    let formData;

    if (isLoggedIn) {

      // 已登录,获取用户数据

      const userData = await this.getUserProfileData();

      formData = {

        isLoggedIn: true,

        formId: formId,

        userName: userData.userName,

        userHeight: userData.userHeight,

        weight: userData.weight,

        updateTime: this.getFormattedTime()

      };

    } else {

      // 未登录,使用默认数据

      formData = {

        isLoggedIn: false,

        formId: formId,

        updateTime: this.getFormattedTime()

      };

    }

    

    // 更新卡片

    const bindingData = formBindingData.createFormBindingData(formData);

    formProvider.updateForm(formId, bindingData);

  } catch (error) {

    console.error(`更新卡片数据失败: ${error}`);

  }

}

卡片交互

为了提升用户体验,我为卡片添加了交互功能,如点击跳转到应用、刷新数据等。

typescript

Apply to UserDataCard...

// 刷新卡片数据

refreshCardData() {

  if (this.refreshing || !this.formId) return;

  

  this.refreshing = true;

  this.rotateAngle = 360;

  

  // 通过消息事件通知卡片更新

  postCardAction(this, {

    action: 'message',

    params: {

      message: 'refresh'

    }

  });

  

  // 重置状态

  this.refreshing = false;

  this.rotateAngle = 0;

}

// 点击卡片跳转

.onClick(() => {

  if (!this.refreshing) {

    if (!this.isLoggedIn) {

      // 未登录状态下点击卡片跳转到登录页面

      postCardAction(this, {

        action: 'router',

        abilityName: 'EntryAbility',

        params: {

          targetPage: 'pages/LoginPage'

        }

      });

    } else {

      // 已登录状态下点击卡片跳转到个人资料页面

      postCardAction(this, {

        action: 'router',

        abilityName: 'EntryAbility',

        params: {

          targetPage: 'pages/ProfilePage'

        }

      });

    }

  }

})

我的卡片开发感悟

卡片服务是鸿蒙系统的一大特色,它让应用能够突破界限,将核心功能和信息直接呈现在桌面上。通过这次实践,我深刻理解了卡片开发的流程和技巧。

卡片开发的关键在于精简与实用的平衡。一方面,卡片空间有限,需要精心设计UI和内容;另一方面,卡片要提供足够的功能和信息,满足用户的日常需求。此外,卡片的性能优化也至关重要,因为它直接影响用户的桌面体验。

未来,我计划进一步优化卡片的视觉效果和交互体验,探索更多创新的展示方式,让用户能够更加便捷地获取和管理健康数据。

Logo

讨论HarmonyOS开发技术,专注于API与组件、DevEco Studio、测试、元服务和应用上架分发等。

更多推荐