Administrator
发布于 2024-06-20 / 30 阅读
0
0

鸿蒙卡片与FormExtensionAbility

本实例将将介绍,如何创建卡片,点击卡片触发更新(触发FormExtensionAbility来更新卡片)

卡片的配置:

{
  "forms": [
    {
      "name": "UsageWidget",
      "displayName": "$string:UsageWidget_display_name",
      "description": "$string:UsageWidget_desc",
      "src": "./ets/widget/UsageWidgetCard.ets",
      "uiSyntax": "arkts",
      "window": {
        "designWidth": 720,
        "autoDesignWidth": true
      },
      "colorMode": "auto",
      "isDynamic": true,
      "isDefault": false,
      "updateEnabled": false,
      "scheduledUpdateTime": "10:30", //定点更新
      "updateDuration": 1,//优先级高于scheduledUpdateTime ;30分钟为单位,1代表30分支
      "defaultDimension": "2*2",
      "supportDimensions": [
        "2*2"
      ]
    },
  ]
}

FormExtensionAbility

1.onAddForm ,当卡片被创建时调用,这里需要返回 formBindingData.FormBindingData;提供卡片数据内容

当长按图标,若配置了3个卡片,弹框会显示三个卡片让用户选择;因此onAddForm 函数也被调用了3次;

当用户选择其中一个,另外的卡片被销毁,因此onRemoveForm被调用2次

2.onRemoveForm,当卡片被销毁时调用;

3.onFormEvent;当点击卡片上的图标,希望触发刷新;可以通过FormExtensionAbility 触发刷新,此时onFormEvent函数会被调用

4.onUpdateForm 当配置了定时或者定点刷新,该函数会被触发;此时完成更新卡片的逻辑

import { formBindingData, FormExtensionAbility, formInfo } from '@kit.FormKit';
import { Want } from '@kit.AbilityKit';
import type Base from '@ohos.base';
import formProvider from '@ohos.app.form.formProvider';
import { Logger, UserAccount } from 'common';
import { formManager} from '../utils/FormManager';
import {UsageFormModal} from  '../model/UsageFormModal'
import { updateManager } from '@kit.StoreKit';
import { FormConstants } from '../constants/FormConstants';
import { UsageUIModal } from '../model/UsageUIModal';
import { FormModal } from '../model/FormModal';

const TAG: string = 'EntryFormAbility';
const DOMAIN_NUMBER: number = 0xFF00;

//卡片业务逻辑模块,提供卡片创建、销毁、刷新等生命周期回调。

export default class EntryFormAbility extends FormExtensionAbility {
  onAddForm(want: Want) {
    // 使用方创建卡片时触发,提供方需要返回卡片数据绑定类

    let userAccount = UserAccount.getAccount();
    let isLogin: boolean = AppStorage.get('isLogin') ?? false


    let formId = ""
    if (want.parameters && want.parameters['ohos.extra.param.key.form_identity'] !== undefined) {
      formId = want.parameters['ohos.extra.param.key.form_identity'].toString();
    }
    let formName = ""
    if (want.parameters && want.parameters['ohos.extra.param.key.form_name'] !== undefined) {
      formName = want.parameters['ohos.extra.param.key.form_name'].toString();
    }
    Logger.info(`FormExtensionAbility onAddForm, fromId = ${formId}  want: ${JSON.stringify(want)} `);


    let formData : UsageFormModal = { formId,  isLogin, phone :userAccount?.userName ?? "", num1:"",num2 : "" ,num3:""  }
    let obj1: formBindingData.FormBindingData = formBindingData.createFormBindingData(formData);
    return obj1;
  }




  private index = 0


  // 若卡片支持触发事件,则需要重写该方法并实现对事件的触发
  async onFormEvent(formId: string, message: string) {
    // Called when a specified message event defined by the form provider is triggered.
    Logger.info(`FormExtensionAbility onFormEvent, formId = ${formId}, message: ${JSON.stringify(message)}`);

    this.index ++
    if(this.index == 10){
      this.index = 0
    }


    let usageUIModal :UsageUIModal = new UsageUIModal( true, "1586758946"+ this.index, "01", "11", "22",)
 	const modal :UsageFormModal = { formId:formId ,isLogin:usageUIModal.isLogin ,phone:usageUIModal.phone ,num1:usageUIModal.num1 ,num2:usageUIModal.num2 ,num3:usageUIModal.num3}
    let formInfo: formBindingData.FormBindingData = formBindingData.createFormBindingData(modal);
    formProvider.updateForm(formId, formInfo).then(() => {
      Logger.info('Operation updateForm success.');
    }).catch((error: Base.BusinessError) => {
      Logger.info(`Operation updateForm failed. Cause: ${JSON.stringify(error)}`);
    })

  }

  onUpdateForm(formId: string) {
    // 若卡片支持定时更新/定点更新/卡片使用方主动请求更新功能,则提供方需要重写该方法以支持数据更新
    Logger.info(
      `FormExtensionAbility onUpdateForm 若卡片支持定时更新/定点更新/卡片使用方主动请求更新功能,则提供方需要重写该方法以支持数据更新`);

	let usageUIModal :UsageUIModal = new UsageUIModal( true, "1586758946"+ this.index, "01", "11", "22",)
 	const modal :UsageFormModal = { formId:formId ,isLogin:usageUIModal.isLogin ,phone:usageUIModal.phone ,num1:usageUIModal.num1 ,num2:usageUIModal.num2 ,num3:usageUIModal.num3}
    let formInfo: formBindingData.FormBindingData = formBindingData.createFormBindingData(modal);
    formProvider.updateForm(formId, formInfo).then(() => {
      Logger.info('Operation updateForm success.');
    }).catch((error: Base.BusinessError) => {
      Logger.info(`Operation updateForm failed. Cause: ${JSON.stringify(error)}`);
    })
    


  }

  // 使用方将临时卡片转换为常态卡片触发,提供方需要做相应的处理
  async onCastToNormalForm(formId: string) {
    Logger.info(`FormExtensionAbility onCastToNormalForm 使用方将临时卡片转换为常态卡片触发`);

  }


  onChangeFormVisibility(newStatus: Record<string, number>) {
    // 需要配置formVisibleNotify为true,且为系统应用才会回调
    // Called when the form provider receives form events from the system.
    Logger.info(
      `FormExtensionAbility onChangeFormVisibility`);


  }

  // 当对应的卡片删除时触发的回调,入参是被删除的卡片ID
  onRemoveForm(formId: string) {
    Logger.info(`FormExtensionAbility onRemoveForm,${formId}`);
    

  }

  // 卡片提供方接收查询卡片状态通知接口,默认返回卡片初始状态。
  onAcquireFormState(want: Want) {
    Logger.info(`FormExtensionAbility onAcquireFormState, 卡片提供方接收查询卡片状态通知接口,默认返回卡片初始状态。`);
    return formInfo.FormState.READY;
  }



};

卡片配置

//重点:卡片上希望触发刷新
postCardAction(this, {
            action: 'message',
            abilityName: this.FormABILITY_NAME,
            params: { target: 'update' }
          });
重点:卡片上希望进入路由
 postCardAction(this, {
        action: 'router',
        abilityName: 'EntryAbility',
        params: { targetPage: this.isLogin ? 'index' : 'login' ,formId:this.formId }
      });
@Entry
@Component
struct UsageWidgetCard {
  readonly TITLE: string = 'Hello World'; // The title.
  readonly ACTION_TYPE: string = 'router'; // The action type.
  readonly ABILITY_NAME: string = 'EntryAbility'; //The ability name.
  readonly FormABILITY_NAME: string = 'EntryFormAbility'; //The FormAbility name.

  @LocalStorageProp('formId') formId: string = '12400633174999288';
  @LocalStorageProp('isLogin') isLogin: boolean = false;
  @LocalStorageProp('phone') phone: string = 'default';
  @LocalStorageProp('num1') num1: string = 'XXX';
  @LocalStorageProp('num2') num2: string = 'XXX';
  @LocalStorageProp('num3') num3: string = 'XXX';

  build() {
    Column() {
      Text(this.formId)
      this.userInfo()

    }
    .onClick(() => {
      postCardAction(this, {
        action: 'router',
        abilityName: 'EntryAbility',
        params: { targetPage: this.isLogin ? 'index' : 'login' ,formId:this.formId }
      });
    })
    .justifyContent(FlexAlign.SpaceAround)
    .padding($r('app.float.x10'))
    .width('100%')
    .height('100%')
  }

  @Builder
  userInfo() {
    Row() {
      Image($r("app.media.card_logo"))
        .width($r("app.float.x25"))
        .height($r("app.float.x25"))

      Text(this.isLogin ? this.getPhone() : "暂未登录")
        .fontSize($r("app.float.x30"))


      Image($r("app.media.refresh"))
        .onClick(() => {//触发卡片刷新
          postCardAction(this, {
            action: 'message',
            abilityName: this.FormABILITY_NAME,
            params: { target: 'update' }
          });
        })
        .visibility(this.isLogin ? Visibility.Visible : Visibility.Hidden)
        .width($r('app.float.x30'))
        .height($r("app.float.x30"))

    }.justifyContent(FlexAlign.SpaceEvenly)
    .width('100%')

  }

  getPhone() {
    if (this.phone) {
      let text = this.phone.slice(0, 4) + "****" + this.phone.slice(7, 11)
      return text
    }
    return ""
  }
}


评论