目录

元服务通过router事件刷新卡片内容

问题现象

元服务卡片与卡片提供方如何交互,如元服务卡片跳转元服务页面,并刷新卡片内容?

背景知识

ArkTS卡片提供页面交互能力,包括卡片与卡片提供方的页面跳转、卡片拉起卡片提供方进程、卡片与卡片提供方的消息传递。

解决方案

可以使用router事件跳转到指定UIAbility,以完成点击卡片跳转至元服务页面,并刷新卡片内容,详细步骤及示例代码如下:

  1. 创建元服务项目,并完成新建元服务卡片。
  2. 删除“WidgetCard.ets”文件中默认生成的卡片代码,新增如下示例代码,通过调用postCardAction接口,触发router事件拉起EntryAbility至前台:
    let storageUpdateRouter = new LocalStorage();
    
    @Entry(storageUpdateRouter)
    @Component
    struct WidgetCard {
      /*
       * The title.
       */
      @LocalStorageProp('title') title: ResourceStr = 'original title';
      /*
       * The action type.
       */
      readonly actionType: string = 'router';
      /*
       * The ability name.
       */
      readonly abilityName: string = 'EntryAbility';
      /*
       * The message.
       */
      readonly message: string = 'update title';
    
      build() {
        Row() {
          Column() {
            Text(this.title)
              .fontSize(14)
              .fontWeight(FontWeight.Medium)
              .fontColor($r('sys.color.font'));
          }
          .width('100%');
        }
        .height('100%')
        .backgroundColor($r('sys.color.comp_background_primary'))
        .onClick(() => {
          postCardAction(this, {
            action: this.actionType,
            abilityName: this.abilityName,
            params: {
              message: this.message
            }
          });
        });
      }
    }
  3. 在EntryAbility的onCreate或者onNewWant生命周期中可以通过入参want获取卡片的formID和传递过来的参数信息,然后调用updateForm接口刷新卡片。
    import { AbilityConstant, UIAbility, Want } from '@kit.AbilityKit';
    import { hilog } from '@kit.PerformanceAnalysisKit';
    import { window } from '@kit.ArkUI';
    import { formBindingData, formInfo, formProvider } from '@kit.FormKit';
    
    const DOMAIN = 0x0000;
    const TAG = 'testTag';
    
    export default class EntryAbility extends UIAbility {
      onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void {
        hilog.info(DOMAIN, TAG, 'onCreate Want:', want.action, launchParam.launchReason);
        this.handleFormRouterEvent(want, 'onCreate');
      }
    
      handleFormRouterEvent(want: Want, source: string): void {
        hilog.info(DOMAIN, TAG, `handleFormRouterEvent ${source}`);
        if (want.parameters && want.parameters[formInfo.FormParam.IDENTITY_KEY] !== undefined) {
          let curFormId = want.parameters[formInfo.FormParam.IDENTITY_KEY].toString();
          let formData: Record<string, string> = {
            'title': 'updated title ' + Date.now()
          };
          let formMsg = formBindingData.createFormBindingData(formData);
          formProvider.updateForm(curFormId, formMsg).then((data) => {
            hilog.info(DOMAIN, TAG, 'updateForm success.', JSON.stringify(data));
          }).catch((error: BusinessError) => {
            hilog.info(DOMAIN, TAG, 'updateForm failed.', JSON.stringify(error));
          });
        }
      }
    
      onNewWant(want: Want, launchParam: AbilityConstant.LaunchParam): void {
        hilog.info(DOMAIN, TAG, 'onNewWant Want:', want.action, launchParam.launchReason);
        this.handleFormRouterEvent(want, 'onNewWant');
      }
    
      onDestroy(): void {
        hilog.info(DOMAIN, TAG, '%{public}s', 'Ability onDestroy');
      }
    
      onWindowStageCreate(windowStage: window.WindowStage): void {
        // Main window is created, set main page for this ability
        hilog.info(DOMAIN, TAG, '%{public}s', 'Ability onWindowStageCreate');
    
        windowStage.loadContent('pages/Index', (err) => {
          if (err.code) {
            hilog.error(DOMAIN, TAG, 'Failed to load the content. Cause: %{public}s', JSON.stringify(err));
            return;
          }
          hilog.info(DOMAIN, TAG, 'Succeeded in loading the content.');
        });
      }
    
      onWindowStageDestroy(): void {
        // Main window is destroyed, release UI related resources
        hilog.info(DOMAIN, TAG, '%{public}s', 'Ability onWindowStageDestroy');
      }
    
      onForeground(): void {
        // Ability has brought to foreground
        hilog.info(DOMAIN, TAG, '%{public}s', 'Ability onForeground');
      }
    
      onBackground(): void {
        // Ability has back to background
        hilog.info(DOMAIN, TAG, '%{public}s', 'Ability onBackground');
      }
    };

常见FAQ

Q:元服务卡片不能自动刷新。

A:服务卡片默认是关闭自动刷新的,需要updateEnabled设置成true手动打开。