鸿蒙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、运行效果如下图所示
相关推荐
爱桥代码的程序媛1 小时前
鸿蒙OpenHarmony【轻量系统芯片移植案例】标准系统方案之瑞芯微RK3568移植案例
嵌入式硬件·harmonyos·鸿蒙·鸿蒙系统·移植·openharmony·鸿蒙开发
AORO_BEIDOU2 小时前
防爆手机+鸿蒙系统,遨游通讯筑牢工业安全基石
5g·安全·智能手机·信息与通信·harmonyos
小强在此17 小时前
【基于开源鸿蒙(OpenHarmony)的智慧农业综合应用系统】
华为·开源·团队开发·智慧农业·harmonyos·开源鸿蒙
PlumCarefree20 小时前
基于鸿蒙API10的RTSP播放器(四:沉浸式播放窗口)
华为·harmonyos
中关村科金1 天前
中关村科金推出得助音视频鸿蒙SDK,助力金融业务系统鸿蒙化提速
华为·音视频·harmonyos
小强在此1 天前
基于OpenHarmony(开源鸿蒙)的智慧医疗综合应用系统
华为·开源·团队开发·健康医疗·harmonyos·开源鸿蒙
奔跑的露西ly1 天前
【鸿蒙 HarmonyOS NEXT】popup弹窗
华为·harmonyos
OH五星上将2 天前
OpenHarmony(鸿蒙南向开发)——轻量和小型系统三方库移植指南(一)
嵌入式硬件·移动开发·harmonyos·openharmony·鸿蒙开发·鸿蒙移植
codes234577892 天前
鸿蒙开发之ArkTS 界面篇 一
harmonyos·arkts·harmonyos next·deveco-studio·鸿蒙界面·鸿蒙界面入门·鸿蒙 index.ets