鸿蒙HarmonyOS开发:如何灵活运用服务卡片提升用户体验

文章目录

一、ArkTS卡片相关模块

ArkTS卡片创建完成后,工程中会新增如下卡片相关文件:卡片生命周期管理文件(EntryFormAbility.ets)、卡片页面文件(WidgetCard.ets)和卡片配置文件(form_config.json)。

二、卡片事件能力说明

ArkTS卡片中提供了postCardAction接口用于卡片内部和提供方应用间的交互,当前支持router、message和call三种类型的事件,仅在卡片中可以调用。

三、卡片事件的主要使用场景

  • router事件:可以使用router事件跳转到指定UIAbility,并通过router事件刷新卡片内容。

  • call事件:可以使用call事件拉起指定UIAbility到后台,并通过call事件刷新卡片内容。

  • message事件:可以使用message拉起FormExtensionAbility,并通过FormExtensionAbility刷新卡片内容。

3.1、使用router事件跳转到指定UIAbility

在卡片中使用postCardAction接口的router能力,能够快速拉起卡片提供方应用的指定UIAbility,因此UIAbility较多的应用往往会通过卡片提供不同的跳转按钮,实现一键直达的效果。

3.1.1、卡片内按钮跳转到应用的不同页面

在UIAbility中接收router事件并获取参数,根据传递的params不同,选择拉起不同的页面。

// Entryability.ts

javascript 复制代码
import UIAbility from '@ohos.app.ability.UIAbility';
import hilog from '@ohos.hilog';
import window from '@ohos.window';

export default class EntryAbility extends UIAbility {
  // 服务卡片跳转的页面
  private selectPage: string = '';
  //当前windowStage
  private currentWindowStage: window.WindowStage | null = null;

  // 如果UIAbility第一次启动,在收到Router事件后会触发onCreate生命周期回调
  onCreate(want, launchParam) {
    // 获取router事件中传递的targetPage参数
    if (want.parameters !== undefined && want.parameters.params) {
      let params = JSON.parse(want.parameters.params)
      this.selectPage = params.targetPage
    }
  }

  // 如果UIAbility已在后台运行,在收到Router事件后会触发onNewWant生命周期回调
  onNewWant(want, launchParam) {
    // 获取router事件中传递的targetPage参数
    if (want.parameters !== undefined && want.parameters.params) {
      let params = JSON.parse(want.parameters.params)
      this.selectPage = params.targetPage
    }
    this.onWindowStageCreate(this.currentWindowStage)
  }

  // 创建主窗口,为此功能设置主页
  onWindowStageCreate(windowStage: window.WindowStage) {
    let targetPage = this.selectPage || "Index"
    targetPage = "pages/" + targetPage
    // 为currentWindowStage赋值
    if (this.currentWindowStage === null) {
      this.currentWindowStage = windowStage;
    }
    windowStage.loadContent(targetPage, (err, data) => {
      if (err.code) {
        hilog.error(0x0000, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err) ?? '');
        return;
      }
      hilog.info(0x0000, 'testTag', 'Succeeded in loading the content. Data: %{public}s', JSON.stringify(data) ?? '');
    });
  }
}
3.1.2、服务卡片的点击跳转事件

在卡片页面中布局两个按钮,点击其中一个按钮时调用postCardAction向指定UIAbility发送router事件,并在事件内定义需要传递的内容。

// WidgetCard.ets

javascript 复制代码
@Entry
@Component
struct WidgetCard {

  build() {
    Column(){
      Button("个人中心")
        .onClick(() => {
          postCardAction(this, {
            "action": "router",
            "abilityName": "EntryAbility",
            "params": {
              "targetPage": "Personals"
            }
          });
        })

      Button("消息列表")
        .onClick(() => {
          postCardAction(this, {
            "action": "router",
            "abilityName": "EntryAbility",
            "params": {
              "targetPage": "Message"
            }
          });
        })
    }
    .width("100%")
    .height("100%")
    .justifyContent(FlexAlign.Center)
  }
}
3.2、通过message事件刷新卡片内容

在卡片页面中可以通过postCardAction接口触发message事件拉起FormExtensionAbility,然后由FormExtensionAbility刷新卡片内容。

3.2.1、在卡片页面调用postCardAction接口触发message事件

在卡片页面通过注册Button的onClick点击事件回调,并在回调中调用postCardAction接口触发message事件拉起FormExtensionAbility。卡片页面中使用LocalStorageProp装饰需要刷新的卡片数据。

// WidgetCard.ets

javascript 复制代码
let storageUpdateByMsg = new LocalStorage();

@Entry(storageUpdateByMsg)
@Component
struct UpdateByMessageCard {
  @LocalStorageProp('title') title: ResourceStr = 'title';
  @LocalStorageProp('detail') detail: ResourceStr = 'detail';

  build() {
    Column() {
      Text(this.title)
      Text(this.detail)
      Button("刷新数据")
        .onClick(() => {
          postCardAction(this, {
            "action": "message",
            "params": {
              "msgTest": "messageEvent"
            }
          });
        })
    }
    .width("100%")
    .height("100%")
    .justifyContent(FlexAlign.Center)
  }
}
3.2.2、onFormEvent生命周期中调用updateForm接口刷新卡片

在FormExtensionAbility的onFormEvent生命周期中调用updateForm接口刷新卡片。

// EntryFormAbility.ts

javascript 复制代码
import formInfo from '@ohos.app.form.formInfo';
import formBindingData from '@ohos.app.form.formBindingData';
import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility';
import formProvider from '@ohos.app.form.formProvider';

export default class EntryFormAbility extends FormExtensionAbility {
  onAddForm(want) {
    // Called to return a FormBindingData object.
    let formData = {};
    return formBindingData.createFormBindingData(formData);
  }

  onFormEvent(formId, message) {
    class FormDataClass {
      title: string = 'Title Update.'; // 和卡片布局中对应
      detail: string = 'Description update success.'; // 和卡片布局中对应
    }

    let formData = new FormDataClass();
    let formInfo: formBindingData.FormBindingData = formBindingData.createFormBindingData(formData);
    formProvider.updateForm(formId, formInfo)
    .then(() => {})
    .catch((error) => {})
  }

};
3.2.2、运行效果如下图所示
相关推荐
lxysbly1 小时前
鸿蒙NDS模拟器app下载
华为·harmonyos
里欧跑得慢1 小时前
Flutter 组件 tavily_dart 的适配 鸿蒙Harmony 实战 - 驾驭 AI 搜索引擎集成、实现鸿蒙端互联网知识精密获取与语义增强方案
flutter·harmonyos·鸿蒙·openharmony·tavily_dart
国医中兴3 小时前
Flutter 三方库 pickled_cucumber 的鸿蒙化适配指南 - 玩转 BDD 行为驱动开发、Gherkin 自动化测试实战、鸿蒙级质量守护神
驱动开发·flutter·harmonyos
里欧跑得慢3 小时前
Flutter 三方库 config 的鸿蒙化适配指南 - 在鸿蒙系统上构建极致、透明、多源叠加的命令行参数解析与环境配置文件加载引擎
flutter·harmonyos·鸿蒙·openharmony
爱学习的小齐哥哥3 小时前
HarmonyOS 5.0元服务深度解析:下一代应用形态的开发与实践指南
华为·harmonyos·harmony pc·harmonyos app
左手厨刀右手茼蒿3 小时前
Flutter 三方库 flutter_azure_tts 深度链接鸿蒙全场景智慧语音中枢适配实录:强势加载云端高拟真情感发音合成系统实现零延迟超自然多端协同-适配鸿蒙 HarmonyOS ohos
flutter·harmonyos·azure
雷帝木木3 小时前
Flutter 三方库 image_compare_2 的鸿蒙化适配指南 - 实现像素级的图像分块对比、支持感知哈希(pHash)与端侧视觉差异检测实战
flutter·harmonyos·鸿蒙·openharmony·image_compare_2
王码码20353 小时前
Flutter 三方库 sum_types 的鸿蒙化适配指南 - 引入函数式编程思维,让鸿蒙应用的状态处理更严谨
flutter·harmonyos·鸿蒙·openharmony·sum_types
加农炮手Jinx3 小时前
Flutter 三方库 cli_script 鸿蒙化极简命令行执行引擎适配探索:在多维沙盒终端环境注入异构 Shell 串联逻辑彻底拔高全自动化容器脚本运维及-适配鸿蒙 HarmonyOS ohos
运维·flutter·harmonyos
亘元有量-流量变现3 小时前
APP自动识别跳转各大应用商店(鸿蒙+iOS+安卓全品牌)|可直接部署落地页源码
android·ios·harmonyos